Tuple Indexing
Tuples support both forward and reverse indexing:
data = (10, 20, 30, 40, 50)
print(data[0]) # Output: 10
print(data[-1]) # Output: 50
Nested tuples can be accessed using multiple indices:
matrix = ((1, 2, 3), (4, 5, 6))
print(matrix[0][1]) # Output: 2
Iteration
Iterate over sequences using while or for:
values = (5, 10, 15, 20)
# Using while
idx = 0
while idx < len(values):
print(values[idx])
idx += 1
# Using for
for item in values:
print(item)
Sets
Sets are unordered collections of unique, hashable elements:
unique_nums = {1, 2, 3}
from_list = set([1, 2, 3, 3]) # Results in {1, 2, 3}
Sets do not support indexing; iterate directly:
for element in unique_nums:
print(element)
Dictionaries
Dictinoaries store key-value pairs with unique keys:
profile = {'name': 'Alice', 'age': 25}
nested = {
'user1': {'id': 101, 'role': 'admin'},
'user2': {'id': 102, 'role': 'guest'}
}
print(nested['user1']['id']) # Output: 101
Iterate over dictionary keys or items:
info = {'a': 1, 'b': 2}
for key in info:
print(info[key])
for key in info.keys():
print(info[key])
Sequence Slicing
Extract subsequences using slicing syntax [start:end:step]:
text = "hello world"
print(text[1:5]) # 'ello'
print(text[::-1]) # 'dlrow olleh' (reversed)
JSON Handling
Convert between Python objects and JSON strings:
import json
records = [{'name': 'Li', 'score': 90}]
json_output = json.dumps(records, ensure_ascii=False)
parsed = json.loads(json_output) # Back to list of dicts
Control Flow
Conditionals
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
else:
print("C")
Check membership with in:
if 'apple' in ['banana', 'apple']:
print("Found")
Loops
# Count occurrences
phrase = "banana"
count = 0
for char in phrase:
if char == 'a':
count += 1
# Nested loops for multiplication table
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}*{i}={i*j}", end='\t')
print()
Use break to exit a loop, continue to skip to the next iteration.
Functions
Define functions with optional parameters and variable arguments:
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
# Variable positional arguments
def sum_all(*numbers):
return sum(numbers)
# Variable keyword arguments
def create_profile(**details):
return details
Higher-order functinos except other functions as arguments:
def apply_operation(func, x, y):
return func(x, y)
result = apply_operation(lambda a, b: a * b, 3, 4) # 12
Object-Oriented Programming
Classes encapsulate data and behavior:
class Person:
def __init__(self, identifier: int, full_name: str):
self.id = identifier
self.name = full_name
def __str__(self) -> str:
return f"Person(id={self.id}, name={self.name})"
def __eq__(self, other) -> bool:
return self.id == other.id if isinstance(other, Person) else False
p1 = Person(1, "Liu Bei")
print(p1) # Uses __str__
Inheritance enables code reuse:
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
Private members use double underscores:
class BankAccount:
def __init__(self):
self.__balance = 0
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
File I/O
Read and write files safely using context managers:
# Reading
with open('data.txt', 'r', encoding='utf-8') as file:
content = file.read()
# Writing
with open('output.txt', 'w', encoding='utf-8') as file:
file.write("New content")
Exception Handling
Catch specific or multiple exceptions:
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Cannot divide by zero")
except (ValueError, TypeError) as e:
print("Invalid input")
else:
print("Success")
finally:
print("Cleanup")
Type Hints
Annotate variables and function signatures for clarity:
from typing import List, Dict
names: List[str] = ["Alice", "Bob"]
metadata: Dict[str, int] = {"count": 42}
def add(x: int, y: int) -> int:
return x + y