Core Language
Python Core Language Python is a high-level, interpreted language valued for its readability, versatility, and rich standard library. It powers web development,…
Python Core Language
Python is a high-level, interpreted language valued for its readability, versatility, and rich standard library. It powers web development, data science, scripting, automation, and machine learning.
Variables & Built-in Types
# Numbers
x: int = 42
y: float = 3.14
z: complex = 2 + 3j
# Strings
name = "Alice"
upper = name.upper() # 'ALICE'
sliced = name[1:4] # 'lic'
f_str = f"Hello, {name}! Age: {30}"
# Booleans
is_valid: bool = True
# None
result = None
print(result is None) # True
# Type checking
print(type(42)) # <class 'int'>
print(isinstance(42, int)) # TrueCollections
# List — mutable, ordered, allows duplicates
fruits = ['apple', 'banana', 'cherry']
fruits.append('date')
fruits.sort()
sliced = fruits[1:3]
# Tuple — immutable, ordered
point = (10, 20)
x, y = point # unpacking
# Dictionary — key-value pairs
user = {'name': 'Alice', 'age': 30}
user['email'] = 'alice@example.com'
name = user.get('name', 'Anonymous')
for key, value in user.items():
print(f"{key}: {value}")
# Set — unordered, unique
unique = {1, 2, 3, 2} # {1, 2, 3}
evens = {2, 4, 6}
odds = {1, 3, 5}
union = evens | odds
intersection = evens & {2, 4, 8}Control Flow
# Conditional expression (ternary)
score = 85
grade = 'A' if score >= 90 else 'B' if score >= 80 else 'C'
# for with enumerate and zip
items = ['a', 'b', 'c']
for i, item in enumerate(items, start=1):
print(f"{i}: {item}")
keys = ['name', 'age']
values = ['Alice', 30]
for k, v in zip(keys, values):
print(f"{k} = {v}")
# while with else
count = 0
while count < 5:
count += 1
else:
print("Completed normally")
# match statement (Python 3.10+)
command = "quit"
match command:
case "quit":
print("Quitting")
case "help":
print("Help menu")
case _:
print(f"Unknown: {command}")Functions
from typing import Optional
# Type annotations and defaults
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
# *args and **kwargs
def log(*messages: str, level: str = "INFO") -> None:
for msg in messages:
print(f"[{level}] {msg}")
log("Starting", "Ready", level="DEBUG")
# Positional-only (/) and keyword-only (*) parameters
def create_user(name: str, /, *, role: str = "user") -> dict:
return {"name": name, "role": role}
# Closures
def make_counter(start: int = 0):
count = start
def increment(step: int = 1) -> int:
nonlocal count
count += step
return count
return increment
counter = make_counter(10)
print(counter()) # 11
print(counter(5)) # 16Comprehensions
# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
# Dict comprehension
word_lengths = {word: len(word) for word in ['hello', 'world', 'python']}
# Set comprehension
unique_lengths = {len(w) for w in ['cat', 'dog', 'elephant', 'ant']}
# Generator expression — lazy, O(1) memory
total = sum(x**2 for x in range(1_000_000))
# Nested (matrix transpose)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in matrix] for i in range(3)]Error Handling
try:
result = 10 / int(input("Enter number: "))
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError as e:
print(f"Invalid input: {e}")
except (TypeError, OverflowError) as e:
print(f"Math error: {e}")
else:
print(f"Result: {result}") # only runs if no exception
finally:
print("Always runs")
# Custom exceptions
class AppError(Exception):
def __init__(self, message: str, code: int = 500):
super().__init__(message)
self.code = code
class NotFoundError(AppError):
def __init__(self, resource: str):
super().__init__(f"{resource} not found", code=404)
# Exception chaining
try:
data = open("config.json")
except FileNotFoundError as e:
raise AppError("Configuration missing") from e