Assign a value to a variable
x = 10
y = 'hello'
z = True
Evaluate a condition and execute code if it's true
if x > y:
# ...
pass
Evaluate another condition if the previous one is false
elif x < y:
# ...
pass
Execute code if all previous conditions are false
else:
# ...
pass
Create a loop that iterates through a sequence
for i in range(10):
# ...
pass
Create a loop that continues as long as the condition is true
while x < 10:
# ...
x += 1
Define a function with a given name
def my_function():
# ...
pass
Define a function with arguments
def my_function(a, b):
# ...
pass
Return a value from a function
def add(a, b):
return a + b
Create a list
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
my_list.remove(1)
my_list.sort()
my_list.reverse()
Create a dictionary
my_dict = {'one': 1, 'two': 2, 'three': 3}
Common dictionary methods
my_dict['four'] = 4
del my_dict['one']
keys = my_dict.keys()
values = my_dict.values()
Define a class with a given name
class MyClass:
# ...
pass
Define a constructor for a class
class MyClass:
def __init__(self, x):
self.x = x
Create a subclass that inherits from a parent class
class MySubclass(MyClass):
# ...
pass
Handle errors and exceptions using try, except, and finally blocks
try:
# ...
pass
except Exception as e:
# ...
pass
finally:
# ...
pass
Raise an exception
if x < 0:
raise ValueError('x must be non-negative')
Read the contents of a file
with open('file.txt', 'r') as f:
content = f.read()
Write to a file
with open('file.txt', 'w') as f:
f.write('Hello, World!')
Import a module
import math
Import specific functions from a module
from math import sqrt, pow
Create a basic generator
def my_generator():
yield 1
yield 2
yield 3
for value in my_generator():
print(value)
Create a generator function using 'yield'
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
Create a generator expression
squares = (x * x for x in range(10))
Create a basic decorator
def my_decorator(func):
def wrapper():
print('Before function call')
func()
print('After function call')
return wrapper
@my_decorator
def my_function():
print('Function called')
my_function()
Create a function decorator
def my_decorator(func):
def wrapper():
# ...
func()
# ...
return wrapper
Create a class decorator
class MyDecorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
# ...
return self.func(*args, **kwargs)
Create a context manager using 'with'
class MyContextManager:
def __enter__(self):
# ...
return self
def __exit__(self, exc_type, exc_value, traceback):
# ...
Create a basic context manager
from contextlib import contextmanager
@contextmanager
def my_context():
print('Entering the context')
yield
print('Exiting the context')
with my_context():
print('Inside the context')
Import the regular expressions module
import re
Search for a pattern in a string
pattern = re.compile('pattern')
result = pattern.search('some text')
Check if a string starts with a pattern
pattern = re.compile('pattern')
result = pattern.match('some text')
Find all occurrences of a pattern in a string
pattern = re.compile('pattern')
result = pattern.findall('some text')
Substitute occurrences of a pattern in a string
pattern = re.compile('pattern')
result = pattern.sub('replacement', 'some text')
Create a list using list comprehension
squares = [x * x for x in range(10)]
Create a list using list comprehension with a condition
even_squares = [x * x for x in range(10) if x % 2 == 0]
Create a basic lambda function
add = lambda x, y: x + y
Pass a lambda function as an argument to another function
sorted_list = sorted(my_list, key=lambda x: x[1])
Slice a list to get a portion of it
my_list = [0, 1, 2, 3, 4, 5]
sub_list = my_list[1:4]
Slice a list with a step
my_list = [0, 1, 2, 3, 4, 5]
even_indices = my_list[::2]
Create a set
my_set = {1, 2, 3}
Common set operations
a = {1, 2, 3}
b = {2, 3, 4}
union = a | b
intersection = a & b
difference = a - b
Create a tuple
my_tuple = (1, 2, 3)
Unpack the elements of a tuple
x, y, z = my_tuple
Create a namedtuple
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
Use enumerate to loop over a sequence with an index
my_list = ['a', 'b', 'c']
for idx, item in enumerate(my_list):
print(idx, item)
Apply a function to each item of an iterable
numbers = [1, 2, 3, 4, 5]
squares = map(lambda x: x * x, numbers)
Filter items of an iterable based on a condition
numbers = [1, 2, 3, 4, 5]
evens = filter(lambda x: x % 2 == 0, numbers)
Create a basic thread
import threading
def my_function():
# ...
pass
thread = threading.Thread(target=my_function)
thread.start()
thread.join()
Create a basic asyncio example
import asyncio
async def my_coroutine():
# ...
pass
async def main():
await my_coroutine()
asyncio.run(main())
Create a list using list comprehension with nested loops
pairs = [(x, y) for x in range(3) for y in range(3)]
Create a basic metaclass
class MyMeta(type):
def __new__(cls, name, bases, dct):
# ...
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=MyMeta):
pass
Use the ternary operator for simple conditional expressions
x = 5
y = 10
max_value = x if x > y else y
Define functions with default arguments
def greet(name, greeting='Hello'):
print(greeting, name)
greet('John')
Define functions with variable arguments
def func(*args):
for arg in args:
print(arg)
func(1, 2, 3)
Define functions with keyword arguments
def func(**kwargs):
for key, value in kwargs.items():
print(key, value)
func(a=1, b=2, c=3)
Use assertions to check for conditions during development
x = 5
assert x > 0, 'x should be positive'
Handle exceptions with try-except blocks
try:
x = 1 / 0
except ZeroDivisionError:
print('Cannot divide by zero')
Create custom exceptions
class MyError(Exception):
pass
try:
raise MyError('An error occurred')
except MyError as e:
print(e)