Python is simple, readable, and versatile. It powers web apps, data science, ML/AI, automation, and APIs — with a massive standard library and 400k+ packages on PyPI.
# Verify install
python --version
# Virtual environment
python -m venv .venv
source .venv/bin/activate # Mac/Linux
# Install packages
pip install requests numpy pandas# hello.py
print("Hello, World!")
name = input("Your name: ")
print(f"Hello, {name}!")name = "Alice" # str
age = 30 # int
height = 5.7 # float
active = True # bool
nothing = None # NoneType
# Type hints (Python 3.5+) — optional but recommended
score: int = 100
label: str = "win"name = "Alice"
print(f"Hello {name}, you are {2024 - 1994} years old")
s = " Hello World "
s.strip() # "Hello World"
s.lower() # " hello world "
s.replace("World", "Python")
s.split() # ["Hello", "World"]
", ".join(["a","b","c"]) # "a, b, c"score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
else:
print("C")
# Ternary
label = "pass" if score >= 60 else "fail"def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
greet("Alice") # "Hello, Alice!"
greet("Alice", "Hi") # "Hi, Alice!"
# *args and **kwargs
def total(*args):
return sum(args)
# Lambda
square = lambda x: x ** 2
# List comprehension
squares = [x**2 for x in range(10)]
even_sq = [x**2 for x in range(10) if x % 2 == 0]| Type | Example | Mutable | Key Methods |
|---|---|---|---|
str | "hello" | No | .upper() .split() .strip() |
int | 42 | No | Arbitrary precision |
list | [1, 2, 3] | Yes | .append() .pop() .sort() |
dict | {"k": "v"} | Yes | .get() .keys() .items() |
set | {1, 2, 3} | Yes | .add() .union() |
tuple | (1, 2, 3) | No | Unpack: a, b = (1, 2) |
class Animal:
def __init__(self, name: str, sound: str):
self.name = name
self._sound = sound
def speak(self) -> str:
return f"{self.name} says {self._sound}"
class Dog(Animal):
def __init__(self, name):
super().__init__(name, "Woof")
# Dataclass
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
label: str = "point"import functools, time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
t = time.time()
result = func(*args, **kwargs)
print(f"{time.time()-t:.4f}s")
return result
return wrapperimport asyncio
async def fetch(url: str) -> str:
await asyncio.sleep(1)
return f"data from {url}"
async def main():
results = await asyncio.gather(
fetch("url1"),
fetch("url2"),
)
asyncio.run(main())try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except (TypeError, ValueError) as e:
print(f"Type or value error: {e}")
else:
print("No error!")
finally:
print("Always runs")DO:
with for file and resource handlingis None not == NoneDON'T:
def f(x=[]): — use Noneexcept: — always specify the exception