The Cheat Sheet

hello There : Python
Variables

Variable Assignment

2.x3.x

Assign a value to a variable

x = 10
y = 'hello'
z = True
Conditionals

if

2.x3.x

Evaluate a condition and execute code if it's true

if x > y:
    # ...
    pass

elif

2.x3.x

Evaluate another condition if the previous one is false

elif x < y:
    # ...
    pass

else

2.x3.x

Execute code if all previous conditions are false

else:
    # ...
    pass
Loops

for

2.x3.x

Create a loop that iterates through a sequence

for i in range(10):
    # ...
    pass

while

2.x3.x

Create a loop that continues as long as the condition is true

while x < 10:
    # ...
    x += 1
Functions

Function Definition

2.x3.x

Define a function with a given name

def my_function():
    # ...
    pass

Function Arguments

2.x3.x

Define a function with arguments

def my_function(a, b):
    # ...
    pass

Function Return

2.x3.x

Return a value from a function

def add(a, b):
    return a + b
Lists

List Creation

2.x3.x

Create a list

my_list = [1, 2, 3, 4, 5]

List Methods

2.x3.x

my_list.append(6)
my_list.remove(1)
my_list.sort()
my_list.reverse()
Dictionaries

Dictionary Creation

2.x3.x

Create a dictionary

my_dict = {'one': 1, 'two': 2, 'three': 3}

Dictionary Methods

2.x3.x

Common dictionary methods

my_dict['four'] = 4
del my_dict['one']
keys = my_dict.keys()
values = my_dict.values()
Classes

Class Definition

2.x3.x

Define a class with a given name

class MyClass:
    # ...
    pass

Constructor

2.x3.x

Define a constructor for a class

class MyClass:
    def __init__(self, x):
        self.x = x

Inheritance

2.x3.x

Create a subclass that inherits from a parent class

class MySubclass(MyClass):
    # ...
    pass
Error Handling

try, except, finally

2.x3.x

Handle errors and exceptions using try, except, and finally blocks

try:
    # ...
    pass
except Exception as e:
    # ...
    pass
finally:
    # ...
    pass

raise

2.x3.x

Raise an exception

if x < 0:
    raise ValueError('x must be non-negative')
File I/O

Read from a file

2.x3.x

Read the contents of a file

with open('file.txt', 'r') as f:
    content = f.read()

Write to a file

2.x3.x

Write to a file

with open('file.txt', 'w') as f:
    f.write('Hello, World!')
Modules

Importing Modules

2.x3.x

Import a module

import math

Importing specific functions

2.x3.x

Import specific functions from a module

from math import sqrt, pow
Generators

Basic Generator

2.x3.x

Create a basic generator

def my_generator():
    yield 1
    yield 2
    yield 3

for value in my_generator():
    print(value)

Generator function

2.x3.x

Create a generator function using 'yield'

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

Generator expression

2.x3.x

Create a generator expression

squares = (x * x for x in range(10))
Decorators

Basic Decorator

2.x3.x

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()

Function decorator

2.x3.x

Create a function decorator

def my_decorator(func):
    def wrapper():
        # ...
        func()
        # ...
    return wrapper

Class decorator

2.x3.x

Create a class decorator

class MyDecorator:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        # ...
        return self.func(*args, **kwargs)
Context Managers

Create a context manager

2.x3.x

Create a context manager using 'with'

class MyContextManager:
    def __enter__(self):
        # ...
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        # ...

Basic Context Manager

2.x3.x

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')
Regular Expressions

re module

2.x3.x

Import the regular expressions module

import re

Search

2.x3.x

Search for a pattern in a string

pattern = re.compile('pattern')
result = pattern.search('some text')

Match

2.x3.x

Check if a string starts with a pattern

pattern = re.compile('pattern')
result = pattern.match('some text')

Find all

2.x3.x

Find all occurrences of a pattern in a string

pattern = re.compile('pattern')
result = pattern.findall('some text')

Substitute

2.x3.x

Substitute occurrences of a pattern in a string

pattern = re.compile('pattern')
result = pattern.sub('replacement', 'some text')
List Comprehensions

Basic List Comprehension

2.x3.x

Create a list using list comprehension

squares = [x * x for x in range(10)]

List Comprehension with Condition

2.x3.x

Create a list using list comprehension with a condition

even_squares = [x * x for x in range(10) if x % 2 == 0]
Lambda Functions

Basic Lambda Function

2.x3.x

Create a basic lambda function

add = lambda x, y: x + y

Lambda Function as Argument

2.x3.x

Pass a lambda function as an argument to another function

sorted_list = sorted(my_list, key=lambda x: x[1])
Slicing

Basic List Slicing

2.x3.x

Slice a list to get a portion of it

my_list = [0, 1, 2, 3, 4, 5]
sub_list = my_list[1:4]

Slicing with Steps

2.x3.x

Slice a list with a step

my_list = [0, 1, 2, 3, 4, 5]
even_indices = my_list[::2]
Sets

Set Creation

2.x3.x

Create a set

my_set = {1, 2, 3}

Set Operations

2.x3.x

Common set operations

a = {1, 2, 3}
b = {2, 3, 4}

union = a | b
intersection = a & b
difference = a - b
Tuples

Tuple Creation

2.x3.x

Create a tuple

my_tuple = (1, 2, 3)

Tuple Unpacking

2.x3.x

Unpack the elements of a tuple

x, y, z = my_tuple
Namedtuples

Namedtuple Creation

2.x3.x

Create a namedtuple

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
Enumerate

Enumerate in Loops

2.x3.x

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)
Map and Filter

Map

2.x3.x

Apply a function to each item of an iterable

numbers = [1, 2, 3, 4, 5]
squares = map(lambda x: x * x, numbers)

Filter

2.x3.x

Filter items of an iterable based on a condition

numbers = [1, 2, 3, 4, 5]
evens = filter(lambda x: x % 2 == 0, numbers)
Threading

Threading Basics

2.x3.x

Create a basic thread

import threading

def my_function():
    # ...
    pass

thread = threading.Thread(target=my_function)
thread.start()
thread.join()
asyncio

Basic asyncio example

3.7+

Create a basic asyncio example

import asyncio

async def my_coroutine():
    # ...
    pass

async def main():
    await my_coroutine()

asyncio.run(main())
List Comprehensions with Nested Loops

List Comprehensions with Nested Loops

2.x3.x

Create a list using list comprehension with nested loops

pairs = [(x, y) for x in range(3) for y in range(3)]
Metaclasses

Basic Metaclass Example

3.x

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
Conditional Expressions

Ternary Operator

2.x3.x

Use the ternary operator for simple conditional expressions

x = 5
y = 10

max_value = x if x > y else y
Function Arguments

Default Arguments

2.x3.x

Define functions with default arguments

def greet(name, greeting='Hello'):
    print(greeting, name)

greet('John')

Variable Arguments

2.x3.x

Define functions with variable arguments

def func(*args):
    for arg in args:
        print(arg)

func(1, 2, 3)

Keyword Arguments

2.x3.x

Define functions with keyword arguments

def func(**kwargs):
    for key, value in kwargs.items():
        print(key, value)

func(a=1, b=2, c=3)
Assertions

Basic Assertions

2.x3.x

Use assertions to check for conditions during development

x = 5
assert x > 0, 'x should be positive'
Exception Handling

Basic Exception Handling

2.x3.x

Handle exceptions with try-except blocks

try:
    x = 1 / 0
except ZeroDivisionError:
    print('Cannot divide by zero')

Custom Exceptions

2.x3.x

Create custom exceptions

class MyError(Exception):
    pass

try:
    raise MyError('An error occurred')
except MyError as e:
    print(e)