Python Cheatsheet
1. Variables and Data Types
name = 'John'
age = 30
is_student = False
height = None
# Complex data types
numbers = [1, 2, 3]
person = { 'name': 'John', 'age': 30 }
set_items = {1, 2, 3}
tuple_items = (1, 2, 3)
2. Control Flow (Conditionals and Loops)
if age > 18:
print('Adult')
else:
print('Minor')
# Loops
for i in range(5):
print(i)
i = 0
while i < 5:
print(i)
i += 1
# Ternary operator
message = 'Adult' if age > 18 else 'Minor'
3. Functions and Lambda Expressions
def greet(name):
return f'Hello, {name}'
print(greet('John'))
# Lambda expression
add = lambda x, y: x + y
print(add(5, 10))
# Keyword arguments and default parameters
def greet(name='Guest', age=18):
return f'Hello, {name}. You are {age}.'
4. Object-Oriented Programming (OOP)
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f'{self.name} makes a sound.')
class Dog(Animal):
def bark(self):
print(f'{self.name} barks.')
rex = Dog('Rex')
rex.speak()
rex.bark()
# Inheritance
class Cat(Animal):
def meow(self):
print(f'{self.name} meows.')
whiskers = Cat('Whiskers')
whiskers.speak()
whiskers.meow()
# Class methods and static methods
class MathUtils:
@classmethod
def add(cls, a, b):
return a + b
@staticmethod
def subtract(a, b):
return a - b
5. Exception Handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f'Error: {e}')
else:
print('No error')
finally:
print('This will always run')
6. List Comprehensions and Generators
# List comprehension
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares)
# Generator expression
gen = (x**2 for x in range(10) if x % 2 == 0)
for value in gen:
print(value)
7. File Handling
with open('file.txt', 'r') as file:
content = file.read()
print(content)
with open('output.txt', 'w') as file:
file.write('Hello, World!')
# Appending to a file
with open('output.txt', 'a') as file:
file.write('\nAppending text')
8. Decorators
def decorator(func):
def wrapper(*args, **kwargs):
print('Before function call')
result = func(*args, **kwargs)
print('After function call')
return result
return wrapper
@decorator
def say_hello(name):
print(f'Hello, {name}')
say_hello('John')
9. Iterators and Generators
# Iterator class
class MyIterator:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current < self.end:
self.current += 1
return self.current - 1
else:
raise StopIteration
for i in MyIterator(1, 5):
print(i)
# Generator function
def countdown(num):
while num > 0:
yield num
num -= 1
for count in countdown(5):
print(count)
10. Async Programming (async/await)
import asyncio
async def fetch_data():
await asyncio.sleep(1)
print('Data fetched after 1 second')
asyncio.run(fetch_data())
# Running multiple coroutines
async def main():
await asyncio.gather(fetch_data(), fetch_data())
asyncio.run(main())
11. Dictionaries
person = { 'name': 'John', 'age': 30 }
print(person['name'])
person['age'] = 31
for key, value in person.items():
print(f'{key}: {value}')
# Dictionary comprehension
squared_numbers = {x: x**2 for x in range(5)}
print(squared_numbers)
12. Modules and Packages
import math
result = math.sqrt(16)
print(result) # 4.0
import os
print(os.getcwd())
# Importing from custom modules
from my_module import my_function
my_function()
13. Context Managers
class CustomContext:
def __enter__(self):
print('Entering context')
def __exit__(self, exc_type, exc_value, traceback):
print('Exiting context')
with CustomContext():
print('Inside context')
14. Regular Expressions
import re
pattern = r'\d+'
result = re.findall(pattern, 'The number is 123')
print(result) # ['123']
# Using re.match and re.search
if re.match(r'\d+', '123abc'):
print('Match found')
15. JSON Handling
import json
data = { 'name': 'John', 'age': 30 }
json_data = json.dumps(data)
parsed_data = json.loads(json_data)
print(parsed_data['name']) # 'John'
16. Datetime and Time
import datetime
now = datetime.datetime.now()
print(now)
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
print(formatted_date)
# Time delta
delta = datetime.timedelta(days=7)
next_week = now + delta
print(next_week)
17. Unit Testing
import unittest
class TestMathOperations(unittest.TestCase):
def test_add(self):
self.assertEqual(1 + 1, 2)
if __name__ == '__main__':
unittest.main()
18. Threading and Multiprocessing
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
import multiprocessing
process = multiprocessing.Process(target=print_numbers)
process.start()
process.join()