Python


Python Cheat Sheet


The site is under development.

Comprehensive Python Cheat Sheet

1. Variables

Syntax: variable_name = value

Variables store data and are used to reference values in your program.

x = 10 # Integer assignment
name = "Alice" # String assignment
is_active = True # Boolean assignment
print(x, name, is_active) # Output: 10 Alice True
Output:
10 Alice True

2. Data Types (int, float, str, bool, None)

Syntax: int, float, str, bool, None

Data types represent the type of data a variable can hold.

x = 10 # int
y = 3.14 # float
name = "Alice" # str
is_active = True # bool
result = None # NoneType
print(type(x), type(y), type(name), type(is_active), type(result)) # Output:
Output:

3. Type Conversion

Syntax: int(value), float(value), str(value), bool(value)

Type conversion allows you to convert one data type to another.

x = "10" # String
y = int(x) # Convert string to integer
print(y, type(y)) # Output: 10

z = 3.14 # Float
w = str(z) # Convert float to string
print(w, type(w)) # Output: 3.14

a = 0 # Integer
b = bool(a) # Convert integer to boolean
print(b) # Output: False
Output:
10
3.14
False

4. Comments (#, """ """ )

Syntax: # single-line comment | """ multi-line comment """

Comments are used to explain code and are ignored by the interpreter.

# This is a single-line comment
x = 10 # Assigning 10 to variable x

""" This is a multi-line comment that spans multiple lines. It is ignored by Python. """ print(x) # Output: 10
Output:
10

5. Basic I/O (print(), input())

Syntax: print(), input()

Basic input/output functions allow you to display information and accept user input.

# print(): Displays output to the console
print("Hello, World!") # Output: Hello, World!

# input(): Accepts user input as a string
name = input("Enter your name: ")
print("Hello, " + name) # Output: Hello,
Output:
Hello, World!
Enter your name: Alice
Hello, Alice

2. Variable Assignment

Syntax: variable_name = value

Variables store values that can be used later. Python is dynamically typed, so you don’t need to declare the type.

# Assign a number to a variable
x = 10
# Print the variable value
print(x)
Output:
10

Arithmetic Operators

Syntax: +, -, *, /, %, **, //

Used for basic mathematical operations like addition, subtraction, etc.

a = 10
b = 3
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a % b) # Modulus (remainder)
print(a ** b) # Exponentiation (power)
print(a // b) # Floor division
Output:
13
7
30
3.3333333333333335
1
1000
3

Comparison Operators

Syntax: ==, !=, >, <, >=, <=

Compare values and return True or False.

a = 5
b = 3
print(a == b) # Equal to
print(a != b) # Not equal to
print(a > b) # Greater than
print(a < b) # Less than
print(a >= b) # Greater than or equal to
print(a <= b) # Less than or equal to
Output:
False
True
True
False
True
False

Logical Operators

Syntax: and, or, not

Used to combine conditional statements.

x = True
y = False
print(x and y) # Returns True if both are True
print(x or y) # Returns True if at least one is True
print(not x) # Reverses the result
Output:
False
True
False

Assignment Operators

Syntax: =, +=, -=, *=, /=, %=, //=, **=

Used to assign and update values of variables.

a = 5
a += 2 # a = a + 2
print(a)
a *= 3 # a = a * 3
print(a)
a -= 1 # a = a - 1
print(a)
Output:
7
21
20

Bitwise Operators

Syntax: &, |, ^, ~, <<, >>

Operate on binary representations of integers.

a = 5 # 0101 in binary
b = 3 # 0011 in binary
print(a & b) # Bitwise AND => 0001 => 1
print(a | b) # Bitwise OR => 0111 => 7
print(a ^ b) # Bitwise XOR => 0110 => 6
print(~a) # Bitwise NOT => flips all bits => -6
print(a << 1) # Left shift => 1010 => 10
print(a >> 1) # Right shift => 0010 => 2
Output:
1
7
6
-6
10
2

Identity Operators

Syntax: is, is not

Check whether two variables refer to the same object in memory.

a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b) # True, same object
print(a is c) # False, same content but different objects
print(a is not c) # True
Output:
True
False
True

Membership Operators

Syntax: in, not in

Check for presence of a value in a sequence (like list, string, etc.).

fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # True
print("orange" not in fruits) # True
Output:
True
True

Data Types

Syntax: type(value)

Python supports various data types like integers, floats, strings, booleans, etc.

a = 5
b = 3.14
c = "Python"
d = True
print(type(a))
print(type(b))
print(type(c))
print(type(d))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>

4. If-Else Condition

Syntax: if condition: ... elif condition: ... else: ...

Conditional statements let you execute code based on logical conditions.

x = 20
if x > 10:
    print("Greater than 10")
elif x == 10:
    print("Equal to 10")
else:
    print("Less than 10")
Output:
Greater than 10

1. Conditional Statements (if, elif, else)

Syntax: if condition: ... | elif condition: ... | else: ...

Conditional statements allow you to execute blocks of code based on specific conditions.

x = 10
if x > 5:
print("x is greater than 5") # Output: x is greater than 5

if x < 5:
print("x is less than 5")
else:
print("x is 5 or greater") # Output: x is 5 or greater

if x == 10:
print("x is 10") # Output: x is 10
elif x == 5:
print("x is 5")
else:
print("x is neither 10 nor 5")
Output:
x is greater than 5
x is 5 or greater
x is 10

2. Loops (for, while)

Syntax: for item in iterable: ... | while condition: ...

Loops allow you to execute a block of code multiple times.

# For Loop (iterates over a sequence like a list)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit) # Output: apple, banana, cherry

# While Loop (runs as long as the condition is True)
count = 0
while count < 3:
print(count) # Output: 0, 1, 2
count += 1
Output:
apple
banana
cherry
0
1
2

3. Loop Control (break, continue, pass)

Syntax: break | continue | pass

Loop control statements alter the behavior of loops.

# break: Exits the loop completely
for i in range(5):
if i == 3:
break # Exits the loop when i equals 3
print(i) # Output: 0, 1, 2

# continue: Skips the current iteration and moves to the next
for i in range(5):
if i == 3:
continue # Skips printing 3
print(i) # Output: 0, 1, 2, 4

# pass: Placeholder that does nothing (useful as a placeholder in empty functions or loops)
for i in range(3):
if i == 2:
pass # Does nothing, but can be used to add functionality later
print(i) # Output: 0, 1, 2
Output:
0
1
2
0
1
2
4
0
1
2

11. While Loop

Syntax: while condition:

The while loop repeats as long as the condition is True.

count = 0
while count < 3:
    print("Counting:", count)
    count += 1
Output:
Counting: 0
Counting: 1
Counting: 2

Filter Function

Syntax: filter(function, iterable)

Filters elements from iterable based on condition.

nums = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)
Output:
[2, 4]

1. Defining Functions (def)

Syntax: def function_name(parameters):

Functions are defined using the def keyword followed by the function name and parameters. The body of the function is indented.

def greet(name):
  print(f"Hello, {name}")

greet("Alice")
Output:
Hello, Alice

2. Arguments (Positional, Keyword, Default, *args, **kwargs)

Syntax: def function(arg1, arg2, ...)

Functions can take various types of arguments: positional, keyword, default, and variable-length arguments using *args and **kwargs.

# Positional Arguments
def greet(name, age):
  print(f"Name: {name}, Age: {age}")

greet("Alice", 30)

# Keyword Arguments
def greet(name, age):
  print(f"Name: {name}, Age: {age}")

greet(age=30, name="Alice")

# Default Arguments
def greet(name, age=30):
  print(f"Name: {name}, Age: {age}")

greet("Alice") # Default age used

# *args
def greet(*args):
  for arg in args:
    print(arg)

greet("Alice", "Bob", "Charlie")

# **kwargs
def greet(**kwargs):
  for key, value in kwargs.items():
    print(f"{key}: {value}")

greet(name="Alice", age=30)
Output:
Name: Alice, Age: 30
Name: Alice, Age: 30
Name: Alice, Age: 30
Alice
Bob
Charlie
name: Alice
age: 30

3. Return Statement (return)

Syntax: return value

The return statement is used to send back a result from a function.

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

result = add(5, 3)
print(result)
Output:
8

4. Lambda Functions (lambda)

Syntax: lambda arguments: expression

A lambda function is a small anonymous function defined using the lambda keyword. It's often used for short operations.

add = lambda a, b: a + b
print(add(5, 3))

square = lambda x: x * x
print(square(4))
Output:
8
16

5. Scope (global, local, nonlocal)

Syntax: global, local, nonlocal

In Python, variables can have different scopes: local, global, and nonlocal. global refers to variables outside any function, local is within a function, and nonlocal refers to variables in the nearest enclosing scope (not global).

x = 10 # Global variable
def local_example():
  x = 5 # Local variable
  print(x)

def global_example():
  global x
  x = 15

def nonlocal_example():
  x = 5
  def inner():
    nonlocal x
    x = 10
  inner()
  print(x)

local_example() # Output: 5
global_example() # Changes global x
print(x) # Output: 15
nonlocal_example() # Output: 10
Output:
5
15
10

Function Definition

Syntax: def function_name(parameters):

Functions group reusable code. You define them using def.

def greet(name):
    # Print a personalized greeting
    print("Hello, " + name + "!")

greet("Alice")
Output:
Hello, Alice!

13. Lambda Function

Syntax: lambda arguments: expression

Anonymous function useful for short operations.

add = lambda x, y: x + y
print(add(3, 4))
Output:
7

Map Function

Syntax: map(function, iterable)

Applies a function to every item in an iterable.

numbers = [1, 2, 3]
result = list(map(lambda x: x*2, numbers))
print(result)
Output:
[2, 4, 6]

1. Lists ([], list())

Syntax: list = [element1, element2, ...] | list = list()

A list is an ordered collection of elements. Lists are mutable (can be changed).

my_list = [1, 2, 3, 4]
print(my_list) # Output: [1, 2, 3, 4]

my_list.append(5) # Add element to the end
print(my_list) # Output: [1, 2, 3, 4, 5]

my_list[0] = 10 # Modify element
print(my_list) # Output: [10, 2, 3, 4, 5]
Output:
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[10, 2, 3, 4, 5]

2. Tuples ((), tuple())

Syntax: tuple = (element1, element2, ...) | tuple = tuple()

A tuple is similar to a list, but it is immutable (cannot be changed after creation).

my_tuple = (1, 2, 3, 4)
print(my_tuple) # Output: (1, 2, 3, 4)

# Tuples are immutable, so the following will raise an error:
# my_tuple[0] = 10 # TypeError: 'tuple' object does not support item assignment
Output:
(1, 2, 3, 4)

3. Sets ({}, set())

Syntax: set = {element1, element2, ...} | set = set()

A set is an unordered collection of unique elements. It cannot contain duplicate values.

my_set = {1, 2, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}

my_set.add(5) # Add element
print(my_set) # Output: {1, 2, 3, 4, 5}

my_set.add(3) # Duplicate value will be ignored
print(my_set) # Output: {1, 2, 3, 4, 5}
Output:
{1, 2, 3, 4}
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}

4. Dictionaries ({}, dict())

Syntax: dict = {'key1': 'value1', 'key2': 'value2', ...} | dict = dict()

A dictionary is an unordered collection of key-value pairs. Keys are unique.

my_dict = {'name': 'Alice', 'age': 30}
print(my_dict) # Output: {'name': 'Alice', 'age': 30}

my_dict['age'] = 31 # Modify value
print(my_dict) # Output: {'name': 'Alice', 'age': 31}

my_dict['city'] = 'New York' # Add new key-value pair
print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York'}
Output:
{'name': 'Alice', 'age': 30}
{'name': 'Alice', 'age': 31}
{'name': 'Alice', 'age': 31, 'city': 'New York'}

5. Strings (str)

Syntax: str = "string" | str = str()

A string is a sequence of characters enclosed in quotes. Strings are immutable.

my_string = "Hello, World!"
print(my_string) # Output: Hello, World!

# String concatenation
new_string = "Hello, " + "Alice!"
print(new_string) # Output: Hello, Alice!

# String slicing
print(my_string[0:5]) # Output: Hello
print(my_string[-6:]) # Output: World!
Output:
Hello, World!
Hello, Alice!
Hello
World!

List Slicing

Syntax: list[start:stop:step]

Extract a portion of a list using slice notation.

nums = [0, 1, 2, 3, 4, 5]
print(nums[1:5:2])
Output:
[1, 3]

List, Dict, Set Comprehensions

Comprehensions are concise ways to build new collections.

List Comprehension

Syntax: [expression for item in iterable]

Syntax: [x for x in iterable]

Creates a new list by applying an expression to each item in an iterable.

squares = [x*x for x in range(5)]
print(squares)
Output:
[0, 1, 4, 9, 16]
# List
squares = [x*x for x in range(3)]
print(squares)

# Dict
squared_dict = {x: x*x for x in range(2)}
print(squared_dict)

# Set
unique = {x % 2 for x in [1, 2, 3, 4]}
print(unique)
Output:
[0, 1, 4]
{0: 0, 1: 1}
{0, 1}

8. Dictionary

Syntax: my_dict = {"key": "value"}

Dictionaries store key-value pairs. Keys must be unique.

person = {"name": "Bob", "age": 25}
print(person["name"]) # Access value by key
Output:
Bob

Class and Object

Syntax: class ClassName: ...

Classes are blueprints for creating objects. They group data and behavior.

Classes define the structure and behavior (methods) for objects. The self keyword refers to the instance itself.

class Person:
  def greet(self):
    print("Hello!")

p = Person() # Create an object of the class
p.greet() # Call the method
Output:
Hello!

2. Constructors (__init__)

Syntax: def __init__(self, ...):

The __init__ method is called automatically when an object is created. It is used to initialize attributes.

class Person:
  def __init__(self, name):
    self.name = name

  def greet(self):
    print("Hello, " + self.name)

p = Person("Alice")
p.greet()
Output:
Hello, Alice

3. Inheritance

Syntax: class Child(Parent):

Inheritance allows a class to derive attributes and methods from another class. Use super() to access the parent class.

class Animal:
  def speak(self):
    print("Animal speaks")

class Dog(Animal):
  def speak(self):
    super().speak() # Call parent method
    print("Dog barks")

d = Dog()
d.speak()
Output:
Animal speaks
Dog barks

4. Encapsulation (Public, Protected, Private)

Syntax: self.var, self._var, self.__var

Python doesn't enforce strict access restrictions, but by convention:

  • self.var is public
  • self._var is protected
  • self.__var is private

class Car:
  def __init__(self):
    self.brand = "Toyota" # Public
    self._engine = "V6" # Protected
    self.__secret_code = "1234" # Private

car = Car()
print(car.brand) # Accessible
print(car._engine) # Accessible but discouraged
print(car._Car__secret_code) # Name mangled access to private
Output:
Toyota
V6
1234

5. Polymorphism

Syntax: Use same method name in different classes

Polymorphism allows different classes to use methods with the same name, enabling interchangeable code.

class Bird:
  def sound(self):
    print("Chirp")

class Cat:
  def sound(self):
    print("Meow")

for animal in [Bird(), Cat()]:
  animal.sound()
Output:
Chirp
Meow

6. Magic Methods (dunder methods)

Syntax: __str__, __len__, __add__, etc.

Magic methods let you define how objects behave with built-in functions or operators.

class Book:
  def __init__(self, title):
    self.title = title

  def __str__(self):
    return f"Book title: {self.title}"

b = Book("Python 101")
print(str(b))
Output:
Book title: Python 101

1. Exception Handling (try, except, else, finally)

Syntax: try: ... except: ... else: ... finally: ...

This block handles errors gracefully. try runs the code. except catches errors. else runs if no error occurs. finally always runs (cleanup code).

try:
  x = 10 / 2 # No error here
except ZeroDivisionError:
  print("Division by zero!")
else:
  print("Division successful")
finally:
  print("Finished block")
Output:
Division successful
Finished block

2. Raising Exceptions (raise)

Syntax: raise ExceptionType("message")

The raise statement allows you to trigger exceptions manually when invalid input or state is detected.

def set_age(age):
  if age < 0:
    raise ValueError("Age cannot be negative")
  print(f"Age is {age}")

set_age(25)
# set_age(-5) # Uncomment to see exception
Output:
Age is 25

3. Built-in Exceptions

Common types: ValueError, TypeError, IndexError, ZeroDivisionError, etc.

These are standard exceptions raised when something goes wrong. Catch them individually or as a group.

try:
  numbers = [1, 2, 3]
  print(numbers[5]) # IndexError
except IndexError:
  print("Invalid index!")

try:
  int("abc") # ValueError
except ValueError:
  print("Cannot convert to int!")

try:
  5 + "string" # TypeError
except TypeError:
  print("Type mismatch!")
Output:
Invalid index!
Cannot convert to int!
Type mismatch!

Ternary Operator

Syntax: x if condition else y

Shorthand for if-else in a single line.

age = 18
result = "Adult" if age >= 18 else "Minor"
print(result)
Output:
Adult

23. Enumerate

Syntax: enumerate(iterable)

Returns index and value while looping through an iterable.

for index, value in enumerate(["a", "b", "c"]):
    print(index, value)
Output:
0 a
1 b
2 c

Decorator

Syntax: @decorator_name

Decorators wrap a function to modify or enhance its behavior.

def my_decorator(func):
    def wrapper():
        print("Before")
        func()
        print("After")
    return wrapper

@my_decorator
def greet():
    print("Hello")

greet()
Output:
Before
Hello
After

Generator

Syntax: yield value

Generators yield values lazily one at a time without storing them all in memory.

Generators produce items one at a time using yield. They're memory-efficient for large sequences.

def gen():
    yield 1
    yield 2
    yield 3

for i in gen():
    print(i)
Output:
1
2
3

def count_up_to(n):
  i = 1
  while i <= n:
    yield i
    i += 1

for number in count_up_to(3):
  print(number)
Output:
1
2
3

1. Importing (import, from ... import)

Syntax: import module_name | from module_name import function_name

You can import an entire module or specific functions/variables from a module.

import math
print(math.sqrt(16)) # Use full module name

from math import sqrt
print(sqrt(16)) # Directly use function without module name
Output:
4.0
4.0

2. Creating Modules

Syntax: Create a Python file (e.g., module_name.py) and use import module_name

A module is simply a Python file with functions, classes, or variables. You can create and import your custom modules.

# In mymodule.py
def greet(name):
  print(f"Hello, {name}")

# In main.py
import mymodule
mymodule.greet("Alice")
Output:
Hello, Alice

3. Packages (__init__.py)

Syntax: __init__.py

A package is a collection of modules. The __init__.py file makes a directory a package and is often empty, or it may execute package-level code.

# Directory structure:
# mypackage/
#   __init__.py
#   module1.py

# In __init__.py (empty or with initialization code)
# In module1.py
def hello():
  print("Hello from module1")

# In main.py
import mypackage.module1
mypackage.module1.hello()
Output:
Hello from module1

4. Standard Library (math, os, sys, datetime, etc.)

Syntax: import module_name

Python has a rich standard library with modules like math, os, sys, datetime, etc.

import math
print(math.pi) # Math library

import os
print(os.getcwd()) # OS library: Get current working directory

import sys
print(sys.version) # Python version

from datetime import datetime
print(datetime.now()) # Get current datetime
Output:
3.141592653589793
/path/to/current/directory
3.9.1 (default, Dec 8 2020, 19:16:56)
2025-04-29 12:34:56.123456

1. Opening Files (open())

Syntax: open(filename, mode)

The open() function is used to open a file. It returns a file object. You must specify the file name and mode (like read, write).

file = open("example.txt", "r")
print(file)
file.close()
Output:
<_io.TextIOWrapper name='example.txt' mode='r' encoding='UTF-8'>

2. Modes (r, w, a, r+, b)

Syntax: "r" = read, "w" = write, "a" = append, "r+" = read/write, "b" = binary mode

Use file modes to determine the operation: "w" overwrites, "a" appends, "r" reads, "r+" updates.

open("file.txt", "r") # Read mode
open("file.txt", "w") # Write mode
open("file.txt", "a") # Append mode
open("file.txt", "r+") # Read & Write
open("file.txt", "rb") # Binary read mode

3. Reading Files

Functions: read(), readline(), readlines()

read() gets all content. readline() reads one line. readlines() gives a list of all lines.

file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Output:
This is line 1
This is line 2

4. Writing Files

Functions: write(), writelines()

write() writes strings. writelines() takes a list of strings.

file = open("example.txt", "w")
file.write("Hello World\n")
file.writelines(["Line 1\n", "Line 2\n"])
file.close()
Output:
File 'example.txt' now contains:
Hello World
Line 1
Line 2

5. Closing Files

Syntax: file.close()

Always close files after use to free system resources.

file = open("example.txt", "r")
data = file.read()
file.close()

6. Context Manager (with)

Syntax: with open(...) as file:

with automatically closes the file. It's the safest and cleanest way to handle files.

with open("example.txt", "r") as file:
  print(file.read())
Output:
Hello World
Line 1
Line 2

Multiprocessing (multiprocessing)

Syntax: multiprocessing.Process(target=...)

Multiprocessing allows parallel execution using separate memory space for each process.

import multiprocessing
def worker():
  print("Process running")

p = multiprocessing.Process(target=worker)
p.start()
p.join()
Output:
Process running

Multithreading (threading)

Syntax: threading.Thread(target=...)

Multithreading runs multiple tasks concurrently in the same process space.

import threading
def show():
  print("Thread running")

t = threading.Thread(target=show)
t.start()
t.join()
Output:
Thread running

Closures

Syntax: Functions inside functions retaining access to enclosing variables.

A closure is a nested function that remembers values from its enclosing scope.

def outer(msg):
  def inner():
    print("Message:", msg)
  return inner

greet = outer("Hello Closure")
greet()
Output:
Message: Hello Closure

Iterators (iter(), next())

Syntax: iter(obj) and next(iterator)

An iterator allows iteration over elements using next() and is created using iter().

numbers = [1, 2, 3]
it = iter(numbers) # Create iterator
print(next(it))
print(next(it))
print(next(it))
Output:
1
2
3

Regular Expressions (re)

Syntax: re.search(), re.match(), re.findall()

Regular expressions are used to match string patterns using the re module.

import re
pattern = r"\d+" # Matches one or more digits
result = re.findall(pattern, "The year is 2025 and the month is 04")
print(result)
Output:
['2025', '04']

JSON (json.loads(), json.dumps())

Syntax: json.loads(json_string), json.dumps(dict_obj)

The json module handles JSON serialization and deserialization.

import json
data = '{"name": "Alice", "age": 30}' # JSON string
python_obj = json.loads(data) # Convert to Python dict
print(python_obj["name"])

# Convert back to JSON string
json_str = json.dumps(python_obj)
print(json_str)
Output:
Alice
{"name": "Alice", "age": 30}

CSV (csv.reader(), csv.writer())

Syntax: csv.reader(file), csv.writer(file)

The csv module is used to read and write CSV files.

import csv
# Writing to a CSV file
with open("sample.csv", "w", newline="") as file:
  writer = csv.writer(file)
  writer.writerow(["Name", "Age"])
  writer.writerow(["Alice", "30"])

# Reading the CSV file
with open("sample.csv", "r") as file:
  reader = csv.reader(file)
  for row in reader:
    print(row)
Output:
['Name', 'Age']
['Alice', '30']

NumPy & Pandas (External Libraries)

Syntax: import numpy as np, import pandas as pd

NumPy is used for numerical arrays and math operations. Pandas is used for data manipulation with DataFrames.

import numpy as np
arr = np.array([1, 2, 3])
print(arr * 2)

import pandas as pd
data = {"Name": ["Alice", "Bob"], "Age": [30, 25]}
df = pd.DataFrame(data)
print(df)
Output:
[2 4 6]
  Name    Age
0    Alice    30
1     Bob     25

HTTP Requests (requests library)

Syntax: requests.get(), requests.post()

The requests library allows you to send HTTP/HTTPS requests easily.

import requests
response = requests.get("https://api.github.com") # Send a GET request
print(response.status_code) # Print HTTP status code
print(response.json()) # Print JSON content if any
Output:
200
{'current_user_url': 'https://api.github.com/user', ...}

Web Scraping (BeautifulSoup)

Syntax: BeautifulSoup(html, 'html.parser')

BeautifulSoup from bs4 is used to extract data from HTML pages.

import requests
from bs4 import BeautifulSoup
url = "https://example.com"
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")
title = soup.title.text # Get the page title
print(title)
Output:
Example Domain

Web Scraping (Scrapy)

Syntax: class MySpider(scrapy.Spider)

Scrapy is a powerful web crawling framework. You define spiders as classes.

import scrapy
class MySpider(scrapy.Spider):
  name = "example"
  start_urls = ['https://example.com']

  def parse(self, response):
    title = response.xpath('//title/text()').get()
    print(title)
Output:
Example Domain

Flask (Minimal Web Framework)

Syntax: @app.route("/"), Flask(__name__)

Flask is a lightweight framework for building web applications quickly.

from flask import Flask
app = Flask(__name__)

@app.route("/") # Define route for the home page
def home():
  return "Hello, Flask!"

if __name__ == "__main__":
  app.run(debug=True)
Output:
Visit http://127.0.0.1:5000/
Hello, Flask!

Django (Full Web Framework)

Syntax: django-admin startproject, def view(request)

Django is a high-level framework for building secure and scalable web apps with ORM, admin, templates, and more.

# In terminal:
django-admin startproject myproject
cd myproject
python manage.py startapp myapp

# In myapp/views.py
from django.http import HttpResponse
def home(request):
  return HttpResponse("Hello, Django!")

# In myproject/urls.py
from django.urls import path
from myapp.views import home
urlpatterns = [
  path("", home),
]
Output:
Visit http://127.0.0.1:8000/
Hello, Django!

Debugging (pdb, breakpoint())

Syntax: import pdb; pdb.set_trace() or breakpoint()

Use the built-in pdb module or breakpoint() function to pause execution and inspect variables step by step.

def add(a, b):
  breakpoint() # Pause execution here
  return a + b

result = add(2, 3)
print(result)
Output:
--Breakpoint at line X--
(Pdb) a
a = 2, b = 3
(Pdb) c
5

2. Unit Testing (unittest)

Syntax: import unittest, class TestName(unittest.TestCase)

unittest is the built-in Python module for writing test cases to verify code functionality.

import unittest

def add(x, y):
  return x + y

class TestAdd(unittest.TestCase):
  def test_add(self):
    self.assertEqual(add(2, 3), 5)

if __name__ == "__main__":
  unittest.main()
Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK

3. Unit Testing (pytest)

Syntax: def test_func(): assert ...

pytest is a third-party framework used for writing simple and scalable test cases using assert statements.

def multiply(x, y):
  return x * y

def test_multiply():
  assert multiply(2, 3) == 6
Output (run using: pytest filename.py):
================= test session starts =================
collected 1 item
test_file.py . [100%]
================== 1 passed in 0.01s ==================

4. Logging (logging)

Syntax: logging.debug(), logging.info(), logging.warning()

The logging module provides a flexible way to report messages during development and production.

import logging
logging.basicConfig(level=logging.DEBUG)

logging.debug("Debugging info") # For development debug
logging.info("Informational message") # General app status
logging.warning("Warning message") # Indicate something unexpected
logging.error("Error message") # Report an error
Output:
DEBUG:root:Debugging info
INFO:root:Informational message
WARNING:root:Warning message
ERROR:root:Error message

1. Virtual Environments (venv, pip)

Syntax: python -m venv env_name | source env_name/bin/activate | pip install package

Use venv to create isolated Python environments for separate projects, preventing package conflicts.

# Create a virtual environment
python -m venv myenv

# Activate the virtual environment (Linux/Mac)
source myenv/bin/activate

# On Windows
myenv\Scripts\activate

# Install packages inside the environment
pip install requests
Output:
Successfully installed requests-x.x.x

2. Docstrings (help(), __doc__)

Syntax: Use triple quotes to document functions/classes, and access using help() or .__doc__

Docstrings describe what your function/class/module does. They help others understand your code.

def greet(name):
  """
  This function greets the person passed in as a parameter.
  """
  print(f"Hello, {name}!")

help(greet)
print(greet.__doc__)
Output:
Help on function greet in module __main__:
greet(name)
    This function greets the person passed in as a parameter.

This function greets the person passed in as a parameter.

3. Annotations (Type Hints)

Syntax: def func(arg: type) -> return_type

Type hints (annotations) help indicate what types of arguments and return values a function expects. They're useful for IDEs and type checkers like mypy.

def add(x: int, y: int) -> int:
  return x + y

print(add(3, 5))
Output:
8