function definition_
def fn(): def fn() -> None: procedure with no arguments
def fn(x, y): def fn(x:Type, y:Type) -> Type: simple function
def fn(x='value', y) def fn(x:Type='value', y:Type) -> Type function with default values
def fn(x, *args, **kwargs) function with positional and keyword arguments
[fn(var) for var in input_list if clause] list comprehension, if is optional
{var:fn(var) for var in input_list if clause} dict comprehension, if is optional
{fn(var) for var in input_list if clause} set comprehension, if is optional
(fn(var) for var in input_list if clause) generator comprehension, if is optional
import json importing the library
dict_string=json.dumps(my_dict) convert Python object to JSON string
dict_pretty_string=json.dumps(my_dict,indent=4) convert Python object to JSON string, but making it pretty

with open("file.json", "w") as json_file:
    json.dump(my_dict, json_file, indent=4)
write JSON data to a file

with open("file.json", "r") as json_file:
    loaded_my_dict = json.load(json_file)
read JSON data from a file
loaded_my_dict_from_str = json.loads(dict_string) convert JSON string back to Python object
import requests importing the library

response = requests.get("")
if response.status_code == 200:
    print("GET:", response.json())
GET Request: Fetch data from a server

payload = {"key1": "value1", "key2": "value2"}
response ="", data=payload)
if response.status_code == 200:
    print("POST:", response.json()["form"])
POST Request: Send data to a server

headers = {"User-Agent": "my-app"}
response = requests.get("", headers=headers)
if response.status_code == 200:
    print("HEADERS:", response.json()["headers"])
sending Headers: Add HTTP headers to your request

    response = requests.get("", timeout=5)
except requests.exceptions.Timeout:
    print("Timeout occurred")
Timeout: Specify a timeout for the request

with requests.Session() as session:
    response = session.get("")
    print("SESSION:", response.json()["cookies"])
Session: Create a session for multiple requests

files = {"file": open("test.txt", "rb")}
response ="", files=files)
if response.status_code == 200:
    print("FILE UPLOAD:", response.json()["files"])
File Upload: Upload a file to a server

response = requests.get("")
response.raise_for_status() # Raises HTTPError for bad responses
Error Handling: Catch and handle HTTP errors
regular expressions
def fn(): def fn() -> None: procedure with no arguments
def fn(): def fn() -> None: procedure with no arguments
def fn(): def fn() -> None: procedure with no arguments
variable scope
Local variable_name = 1
Global global variable_name = 1
Non Local nonlocal variable_name = 1
class definition

class Animal:
    species = "Unknown"  # Class Variable
    def __init__(self, name):  # Instance Constructor = name
    def describe(self):  # Instance Method
        return f"{} is a {self.species}"
    def is_alive(lifespan, current_age):  # Static Method
        return current_age < lifespan
    def set_species(cls, new_species):  # Class Method 
        cls.species = new_species
s = {1, 2, 3} Creation of a set
s & z s.__and__(z) Intersection of s and z
s &= z s.__iand__(z) s updated with intersection of s and z
s | z s.__or__(z) Union of s and z
s |= z s.__ior__(z) s updated with union of s and z
dictionary wih default values

import collections
my_dict, key, new_value = {}, "key", 1
# using defaultdict
coll = collections.defaultdict(list)
# using setdefault
my_dict.setdefault("key", []).append(new_value)
if key not in my_dict:
    my_dict[key] = []
Local variable_name = 1
Local variable_name = 1
Local variable_name = 1
Local variable_name = 1
Local variable_name = 1
Local variable_name = 1
ElementTree parse XML trees
asyncio asynchronous functionality
reduce another functools function
partial Partial functions
mypy Cheching types
pytest Testing
time Managing time
class inheritance

class Dog(Animal):
    # Override class variable
    species = "Canine"
    # Overide and extend
    def __init__(self, n, breed): 
        self.breed = breed
    # Additional instance method
    def fetch(self, thing):
        return f"{} fetched the {thing}"
class properties

class Person:
    def __init__(self, name, age): = name
        self._age = age 
    def age(self):
        return self._age
    def age(self, value):
        if value < 0:
            print("Age cannot be negative!")
            self._age = value
abstract class

from abc import ABC, abstractmethod
class Shape(ABC):
    def area(self):
boilerplate main

if __name__ == "__main__":
expression operators

yield x
Generator function send protocol

lambda args: expression
Anonymous function generation

x if y else z
Ternary operation

x or y
Logical OR

x and y
Logical AND

not x
Logical negation

x in y
x not in y
Membership(iterables, sets)

x is y
x is not y
Object identity test

x < y
x <= y
x > y
x >= y
Magnitude comparison, set subset and superset

x == y
x != y
Value equality operators

x | y
Bitwise OR, set union

x ^ y
Bitwise XOR, set symmetric difference

x & y
Bitwise AND, set intersection

x << y
x >> y
Shift x left or right by y bits

x + y
Addition, concatenation

x - y
Subtraction, set difference

x * y
Multiplication, repetition

x % y
Remainder, format

x / y
x // y
Division: true and floor


Bitwise NOT (inversion)

x ** y
Power (exponentiation)