class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"Hi, I'm {self.name}"
# Create instance
person = Person("Alice", 30)
print(person.introduce())
Common Built-in Functions
python
len(collection) # Length
max(numbers) # Maximum value
min(numbers) # Minimum value
sum(numbers) # Sum of numbers
sorted(collection) # Return sorted copy
type(variable) # Get type
str(value) # Convert to string
int(value) # Convert to integer
float(value) # Convert to float
List Comprehensions
python
# Basic syntax: [expression for item in iterable]
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
File Operations
python
# Reading
with open("file.txt", "r") as file:
content = file.read()
# Writing
with open("file.txt", "w") as file:
file.write("Hello, World!")
Exception Handling
python
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
finally:
print("This always runs")
Imports
python
import math
from datetime import datetime
import numpy as np # Common alias
from collections import Counter
numbers = [3, 1, 4, 1, 5]
numbers.append(9) # Add to end
numbers.insert(0, 2) # Insert at index
numbers.remove(1) # Remove first occurrence
numbers.pop() # Remove and return last
numbers.sort() # Sort in place
numbers.reverse() # Reverse in place
This covers the most frequently used Python syntax and features for everyday programming tasks.