Dark versionDefault version

Python Cheatsheet

โœ๏ธ Basic

# Comments
# Single line comment
'''Multi-line comment'''

# Variables
x = 10
name = "Safiul"
pi = 3.14

๐ŸงŠ Data Types

# Numbers
int, float, complex

# Strings
s = "Hello"
s.lower(), s.upper(), s[0], s[1:3], len(s)

# Booleans
True, False

# Type Conversion
int("10"), str(123), float("3.14")

๐Ÿ“š Collections

# List
lst = [1, 2, 3]
lst.append(4), lst.pop(), lst[0], len(lst)

# Tuple
t = (1, 2)
t[0]

# Set
s = {1, 2, 3}
s.add(4), s.remove(2)

# Dictionary
d = {"a": 1, "b": 2}
d["a"], d.get("c", 0), d.keys(), d.values()

๐Ÿงฉ Control Flow

# If
if x > 5:
    print("Large")

# For loop
for i in range(5):
    print(i)

# While loop
while x < 5:
    x += 1

๐Ÿง  Comprehensions

Comprehension refers to a concise way to create collections like lists, dictionaries, sets, or even generators using a compact, readable syntax.

# List
squares = [x**2 for x in range(5)]

# Dict
square_map = {x: x**2 for x in range(5)}

โš™๏ธ Functions

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

# Lambda
square = lambda x: x**2

๐Ÿงฐ Modules

import math
math.sqrt(16)

from random import randint
randint(1, 10)

๐Ÿงฑ Classes

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

    # Function
    def greet(self):
        return f"Hello, {self.name}"

    # Destructor
    def __del__(self):
        print(f"Destructor called for {self.name}")

โ™ป๏ธ Classes with Context Management

Guarantees cleanup like closing a file even if an exception occurs inside the with block. This is more reliable and predictable than __del__.

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

    def __enter__(self):
        print(f"{self.name} has entered the context.")
        return self  # makes 'as' variable point to this object

    def __exit__(self, exc_type, exc_value, traceback):
        print(f"{self.name} has exited the context.")

# Usage
with Person("Safiul") as p:
    print(f"Hello, {p.name}!")

๐Ÿงฌ Classes with Inheritance & Abstraction

# Class inheritance
class Animal:
    def speak(self):
        return "Generic sound"

class Dog(Animal):  # Dog extends Animal
    def speak(self):
        return "Bark"

d = Dog()
print(d.speak())  # Output: Bark

# Using super()
class Parent:
    def greet(self):
        print("Hello from Parent")

class Child(Parent):
    def greet(self):
        super().greet()
        print("Hello from Child")

c = Child()
c.greet()
# Output:
# Hello from Parent
# Hello from Child

# Class abstraction
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def area(self):
        return 3.14 * 2 * 2

# s = Shape()  # โŒ Error: can't instantiate abstract class
c = Circle()
print(c.area())  # โœ… Output: 12.56

๐Ÿงผ Cleanup & Destruction

Python uses automatic garbage collection to manage memory, so you usually don’t need to delete objects manually.

class Demo:
    def __del__(self):
        print("Destructor called")

obj = Demo()
del obj  # Optional: triggers __del__ immediately

โš ๏ธ Exception Handling

try:
    1 / 0
except ZeroDivisionError:
    print("Can't divide by zero!")
finally:
    print("Done")

๐Ÿ“ File I/O

# Write
with open("file.txt", "w") as f:
    f.write("Hello")

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

๐Ÿ“ฆ Importing & Exporting Modules

# Import entire module
import math
print(math.sqrt(16))  # Output: 4.0

# Import specific items
from math import sqrt, pi
print(sqrt(25))  # Output: 5.0
print(pi)        # Output: 3.1415...

# Import with alias
import numpy as np
print(np.array([1, 2, 3]))

# Wildcard import
from math import *
print(sin(pi))  # Can cause name clashes

# Exporting own module
# file: custom.py
def greet(name):
    return f"Hello, {name}"

# file: main.py
from custom import greet
print(greet("Safiul"))

โœ… Useful Built-ins

len(), type(), isinstance(), sorted(), sum(), max(), min(), zip(), enumerate()