⬅ Previous TopicPHP Cheat Sheet
Next Topic ⮕Rust Cheat Sheet
Python is dynamically typed. Variable types are inferred at runtime.
x = 5 # int
y = 3.14 # float
name = "Alice" # str
is_active = True # bool
Python is dynamically typed. Variable types are inferred at runtime.
x = 5 # int
y = 3.14 # float
name = "Alice" # str
is_active = True # bool
Convert between types using built-in functions.
int("3") # 3
str(42) # '42'
float("2.5") # 2.5
bool(0) # False
a + b, a - b, a * b, a / b, a % b, a ** b, a // b
a == b, a != b, a > b, a < b, a >= b, a <= b
and, or, not
a & b, a | b, a ^ b, ~a, a << b, a >> b
=, +=, -=, *=, /=, %=, //=, **=
s = "hello"
s.upper(), s.lower(), s.capitalize()
s.replace("h", "H")
s.split("e")
"-".join(["a", "b"])
name = input("Enter your name: ")
print(f"Hello, {name}!")
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
for i in range(5):
print(i)
count = 0
while count < 5:
print(count)
count += 1
for i in range(5):
if i == 3:
break # exits loop
if i == 1:
continue # skips to next iteration
print(i)
for j in range(3):
pass # placeholder
squares = [x**2 for x in range(5)]
squares = {x: x**2 for x in range(5)}
unique = {x % 3 for x in range(10)}
def greet(name, msg="Hello"):
print(f"{msg}, {name}!")
greet("Alice")
greet("Bob", "Hi")
square = lambda x: x * x
print(square(5))
from functools import reduce
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x*x, nums))
evens = list(filter(lambda x: x%2 == 0, nums))
sum_all = reduce(lambda x, y: x + y, nums)
def decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits.remove("banana")
print(fruits[0])
coordinates = (10, 20)
print(coordinates[1])
person = {"name": "Alice", "age": 30}
print(person["name"])
person["age"] = 31
unique_numbers = {1, 2, 3, 2}
unique_numbers.add(4)
stack = []
stack.append(1)
stack.pop()
from collections import deque
queue = deque([1, 2, 3])
queue.append(4)
queue.popleft()
from collections import Counter
c = Counter("hello")
from collections import defaultdict
d = defaultdict(int)
d["a"] += 1
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)
from collections import deque
dq = deque([1, 2, 3])
dq.appendleft(0)
import math
from math import sqrt
import os as operating_system
Popular modules: math
, random
, datetime
, os
, sys
, re
import datetime
now = datetime.datetime.now()
# Directory structure:
# mypackage/
# ├── __init__.py
# └── module.py
from mypackage import module
module.my_function()
python -m venv env
source env/bin/activate # On Windows: envScriptsactivate
pip install -r requirements.txt
# Writing to a file
with open("example.txt", "w") as f:
f.write("Hello, World!")
# Reading from a file
with open("example.txt", "r") as f:
content = f.read()
with
ensures proper acquisition and release of resources like files.
with open("file.txt", "r") as file:
data = file.read()
import csv
with open("data.csv", newline="") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
import json
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data)
parsed = json.loads(json_str)
try:
x = 1 / 0
except ZeroDivisionError as e:
print("Cannot divide by zero:", e)
finally:
print("Cleanup actions")
raise ValueError("Invalid input")
class MyError(Exception):
pass
raise MyError("Something went wrong")
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, my name is {self.name}")
p = Person("Alice")
p.greet()
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Animal:
def speak(self):
print("Generic sound")
class Dog(Animal):
def speak(self):
print("Bark")
class Base:
def greet(self):
print("Hello")
class Derived(Base):
def greet(self):
print("Hi")
# Polymorphism
for obj in [Base(), Derived()]:
obj.greet()
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return f"Book: {self.title}"
def __repr__(self):
return f"Book('{self.title}')"
nums = [1, 2, 3]
it = iter(nums)
print(next(it))
def countdown(n):
while n > 0:
yield n
n -= 1
for val in countdown(3):
print(val)
def outer(x):
def inner(y):
return x + y
return inner
add_five = outer(5)
print(add_five(3))
class MyContext:
def __enter__(self):
print("Enter")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exit")
with MyContext() as ctx:
print("Inside block")
def greet(name: str) -> str:
return "Hello " + name
import threading
def worker():
print("Working")
thread = threading.Thread(target=worker)
thread.start()
thread.join()
from multiprocessing import Process
def worker():
print("Working in another process")
process = Process(target=worker)
process.start()
process.join()
import asyncio
async def say_hello():
await asyncio.sleep(1)
print("Hello")
asyncio.run(say_hello())
len(), type(), range(), enumerate(), zip()
sorted(), reversed(), any(), all(), sum()
import math
math.sqrt(16)
import datetime
datetime.datetime.now()
import os
os.getcwd()
import sys
print(sys.version)
import re
re.match(r"d+", "123abc")
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--name")
args = parser.parse_args()
print(f"Hello {args.name}")
__init__, __str__, __repr__, __len__, __getitem__,
__setitem__, __delitem__, __iter__, __next__, __contains__
import requests
response = requests.get("https://api.example.com")
print(response.json())
Comments and Docstrings