Python comprehensive cheat sheet
print("Hello, World!")
print(type(3.14)) # <class "float">
print(isinstance("a", str)) # True
int("5") # 5
float("3.14") # 3.14
str(5) # "5"
list("abc") # ["a","b","c"]
[x*x for x in range(5)] # [0, 1, 4, 9, 16]
[x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
matrix = [[1,2],[3,4]]
flattened = [num for row in matrix for num in row] # [1,2,3,4]
x = 10
if x > 5:
print("Greater")
elif x == 5:
print("Equal")
else:
print("Smaller")
for i in range(3):
print(i)
for i in [1,2,3]:
print(i)
i = 0
while i < 3:
print(i)
i += 1
def add(a, b):
return a + b
def greet(name="World"):
print(f"Hello, {name}")
def func(*args, **kwargs):
print(args)
print(kwargs)
square = lambda x: x * x
print(square(5)) # 25
nums = [1, 2, 3]
squares = list(map(lambda x: x*x, nums))
nums = [1, 2, 3, 4]
evens = list(filter(lambda x: x % 2 == 0, nums))
from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
class Car:
def __init__(self, brand):
self.brand = brand
def start(self):
print(f"{self.brand} is starting")
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Woof!")
class Example:
@staticmethod
def static():
print("Static method")
@classmethod
def cls(cls):
print("Class method")
def my_decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@my_decorator
def greet():
print("Hello!")
def counter():
for i in range(3):
yield i
it = iter([1,2,3])
print(next(it)) # 1
def counter():
for i in range(3):
yield i
try:
x = 1 / 0
except ZeroDivisionError as e:
print("Error:", e)
try:
x = 1
except:
pass
else:
print("No error!")
finally:
print("Always runs")
with open("file.txt", "r") as f:
content = f.read()
with open("file.txt", "w") as f:
f.write("Hello!")
with open("file.txt") as f:
for line in f:
print(line.strip())
import math
print(math.sqrt(16))
import random
print(random.randint(1, 100))
python -m venv venv
source venv/bin/activate
import unittest
class TestAdd(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
if __name__ == "__main__":
unittest.main()
def add(a: int, b: int) -> int:
return a + b
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
from pathlib import Path
p = Path("file.txt")
print(p.exists())
import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is an info message")
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--foo")
args = parser.parse_args()
import asyncio
async def main():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(main())
with open("file.txt") as f:
data = f.read()
from contextlib import contextmanager
@contextmanager
def my_cm():
print("Enter")
yield
print("Exit")
with my_cm():
print("Inside")