Python

Python Cheat Sheets

This Python cheat sheet tries to provide basic reference for beginner and advanced developers.

Getting Started

// Hello World

print("Hello, World!")
Basic print statement

// Basic Commands

Comment
# Single line comment
Multiline Comment
""" Multiline Comment """
Variable Assignment
x = 5
Output
print(x)
Input
input("Enter something: ")

Data Types

// Primitive Data Types

int
Integer (x = 1)
float
Floating point (y = 3.14)
str
String (s = "hello")
bool
Boolean (b = True)
list
List (l = [1,2,3])
tuple
Tuple (t = (1,2,3))
set
Set (s = {1,2,3})
dict
Dictionary (d = {"a": 1})

// Type Checking

print(type(3.14))  # <class "float">
print(isinstance("a", str))  # True
type() and isinstance()

// Type Conversion Functions

int()
int("5") -> 5
float()
float("3.14") -> 3.14
str()
str(5) -> "5"
list()
list("abc") -> ["a","b","c"]

// Type Conversion Examples

int("5")  # 5
float("3.14")  # 3.14
str(5)  # "5"
list("abc")  # ["a","b","c"]
Basic type conversion examples

List Comprehensions

// Simple List Comprehension

[x*x for x in range(5)]  # [0, 1, 4, 9, 16]
List Comprehension

// Conditional List Comprehension

[x for x in range(10) if x % 2 == 0]  # [0, 2, 4, 6, 8]
Conditional list comprehension

// Nested List Comprehension

matrix = [[1,2],[3,4]]
flattened = [num for row in matrix for num in row]  # [1,2,3,4]
Nested list comprehension

Control Flow

// if-elif-else

x = 10
if x > 5:
    print("Greater")
elif x == 5:
    print("Equal")
else:
    print("Smaller")
Conditional Statements

// for Loop

for i in range(3):
    print(i)

for i in [1,2,3]:
    print(i)
Iterating with for

// while Loop

i = 0
while i < 3:
    print(i)
    i += 1
While loop

// Loop Control Keywords

break
Exit the loop
continue
Skip to next iteration
pass
Do nothing (placeholder)

Functions

// Function Definition

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

// Default Arguments

def greet(name="World"):
    print(f"Hello, {name}")
Default arguments

// *args and **kwargs

def func(*args, **kwargs):
    print(args)
    print(kwargs)
args and kwargs

// Function Attributes

__name__
Function name
__doc__
Function docstring

Lambda, map, filter, reduce

// Lambda Function

square = lambda x: x * x
print(square(5))  # 25
Lambda function

// map()

nums = [1, 2, 3]
squares = list(map(lambda x: x*x, nums))
map() function

// filter()

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

// reduce()

from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
reduce() function

Object-Oriented Programming (OOP)

// Class Definition

class Car:
    def __init__(self, brand):
        self.brand = brand
    def start(self):
        print(f"{self.brand} is starting")
class keyword

// OOP Terms

self
Reference to the instance
__init__
Constructor method
method
Function defined in a class

// Inheritance

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

class Dog(Animal):
    def speak(self):
        print("Woof!")
Inheritance

// Classmethod & Staticmethod

class Example:
    @staticmethod
    def static():
        print("Static method")
    @classmethod
    def cls(cls):
        print("Class method")
Classmethod and Staticmethod

Decorators

// Simple Decorator

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

// Using @decorator

@my_decorator
def greet():
    print("Hello!")
Using @decorator

Generators & Iterators

// Generator Function

def counter():
    for i in range(3):
        yield i
Generator function

// Generator Features

yield
Returns a value and pauses the function
next()
Gets the next value
iter()
Returns an iterator

// Iterator Protocol

it = iter([1,2,3])
print(next(it))  # 1
Iterator protocol

// Generator Example

def counter():
    for i in range(3):
        yield i
Generator example

Error Handling

// try-except

try:
    x = 1 / 0
except ZeroDivisionError as e:
    print("Error:", e)
try-except block

// finally and else

try:
    x = 1
except:
    pass
else:
    print("No error!")
finally:
    print("Always runs")
finally and else

// Common Exceptions

ValueError
Raised when a function receives the wrong value type
TypeError
Raised when an operation is applied to an object of inappropriate type
KeyError
Raised when a dictionary key is not found

File I/O

// Reading a File

with open("file.txt", "r") as f:
    content = f.read()
Reading a file

// Writing to a File

with open("file.txt", "w") as f:
    f.write("Hello!")
Writing to a file

// Reading Line by Line

with open("file.txt") as f:
    for line in f:
        print(line.strip())
Reading line by line

Modules & Packages

// Importing Modules

import math
print(math.sqrt(16))
Importing modules

// Importing Modules

import random
print(random.randint(1, 100))
Importing modules

// Common Modules

os
Operating system interfaces
sys
System-specific parameters and functions
datetime
Date and time manipulation
itertools
Iterator building blocks
collections
High-performance container datatypes

Virtualenv & pip

// pip Commands

pip install package
Install a package
pip uninstall package
Uninstall a package
pip list
List installed packages
pip freeze
Output installed packages in requirements format

// Create Virtual Environment

python -m venv venv
source venv/bin/activate
Creating a virtual environment

Testing

// Simple Test (unittest)

import unittest

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

if __name__ == "__main__":
    unittest.main()
Simple unittest

Type Hints & Typing

// Type Hints

def add(a: int, b: int) -> int:
    return a + b
Type hints

// Common Typing Types

List
List[int]
Dict
Dict[str, int]
Optional
Optional[str]
Union
Union[int, str]

Dataclasses

// Basic Dataclass

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int
Basic dataclass

Pathlib

// Using Pathlib

from pathlib import Path
p = Path("file.txt")
print(p.exists())
Using pathlib

Logging

// Basic Logging

import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is an info message")
Basic logging

Argparse

// Basic Argparse

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--foo")
args = parser.parse_args()
Basic argparse

// Argparse Resources

Asyncio

// Basic Async Function

import asyncio

async def main():
    print("Hello")
    await asyncio.sleep(1)
    print("World")

asyncio.run(main())
Basic async function

Context Managers

// with Statement

with open("file.txt") as f:
    data = f.read()
with statement

// Custom Context Manager

from contextlib import contextmanager

@contextmanager
def my_cm():
    print("Enter")
    yield
    print("Exit")

with my_cm():
    print("Inside")
Custom context manager

Built-in Functions

// Common Built-ins

len()
Get length of a sequence
sum()
Sum of elements
min(), max()
Minimum/maximum value
sorted()
Return a sorted list
enumerate()
Get index and value in a loop
zip()
Combine multiple iterables

Popular Libraries

Land the career of your dreams!

Get inspired, learn, join competitions and grow in your job!

Sign up now