Complete Python Cheat Sheet

To code with python programming language in our system first we have to had python installed in our system. To install the latest version of python we need to get the latest version from the official website: https://python.org. Then we need to install it to our system. We can use different IDE such as IntelliJ or VS Code to compile our python code.

To check python version in your system go to terminal or Command Prompt:

py -3 --version

For Mac or Linux system:

python3 --version

Your First code in Python

Open your code editor & write the code line:

print("Hello, world!")

example 2:

greetings = 'Hello World'
print(greetings)

Variables

The correct syntax of declaring various variables in python:

name = "Manan"
age = 20
is_programmer = True

Example 2:

name: str = "manan"
age: int = 25
height: float = 5.9
is_student: bool = True

Example 3:

age: int = 26        # for whole numbers
height: float = 5.9  # for decimal numbers

❌ Not Allowed:

  • Starting with a number: 1age ❌
  • Special characters: @name, #age ❌
  • Keywords like if, while, class, etc.

Operators

Arithmetic Operators

OperatorDescriptionExample (a = 10, b = 3)Result
+Additiona + b13
-Subtractiona - b7
*Multiplicationa * b30
/Division (float)a / b3.333...
//Floor Divisiona // b3
%Modulus (remainder)a % b1
**Exponentiationa ** b1000

Comparison (Relational) Operators

OperatorDescriptionExample (a = 10, b = 3)Result
==Equal toa == bFalse
!=Not equal toa != bTrue
>Greater thana > bTrue
<Less thana < bFalse
>=Greater or equala >= bTrue
<=Less or equala <= bFalse

Logical Operators

OperatorDescriptionExampleResult
andTrue if both are true(a > 5 and b < 5)True
orTrue if at least one is true(a < 5 or b < 5)True
notReverses the resultnot(a > 5)False

Assignment Operators

OperatorExampleSame As
=x = 5
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
//=x //= 3x = x // 3
%=x %= 3x = x % 3
**=x **= 3x = x ** 3

Bitwise Operators

OperatorDescriptionExample (a = 5, b = 3)Result
&ANDa & b0101 & 00111
``OR`a
^XORa ^ b6
~NOT~a-6
<<Left shifta << 110
>>Right shifta >> 12

Membership Operators

OperatorDescriptionExampleResult
inReturns True if found'a' in 'apple'True
not inReturns True if not found'z' not in 'apple'True

Identity Operators

OperatorDescriptionExampleResult
isTrue if same objecta is bFalse
is notTrue if not same objecta is not bTrue

Data Types

A data type defines what kind of value a variable holds — numbers, text, lists, etc.
Python automatically detects the type when you assign a value.

# Numeric Types
x = 5           # int
y = 3.14        # float
z = 2 + 3j      # complex

# String Type (str)
name = "Manan Academy"
print(name)
print(name[0])       # Access character
print(name.upper())  # Convert to uppercase
print(len(name))     # Get length

# Boolean Type (bool)
is_sunny = True
is_raining = False
print(is_sunny and not is_raining)  # True

# Sequence Types (list)
fruits = ["apple", "banana", "cherry"] #Mutable (can be changed).
fruits.append("mango")
print(fruits)

# Sequence Types (tuple)
colors = ("red", "green", "blue") #Immutable (cannot be changed).
print(colors[1])  # green

# Sequence Types (range)
numbers = range(5)  # 0,1,2,3,4
for n in numbers:
    print(n)

# Set Types
nums = {1, 2, 3, 3, 2}
print(nums)  # {1, 2, 3}
nums.add(4)

# Dictionary Type (dict)
person = {
    "name": "Manan",
    "age": 24,
    "job": "Photographer"
}
print(person["name"])  # Manan

# None Type
x = None
print(x)        # None
print(type(x))  # <class 'NoneType'>

Conditions

marks = 75

if marks >= 80:
    print("A+")
elif marks >= 70:
    print("A")
elif marks >= 60:
    print("B")
else:
    print("Fail")

Nested if: You can put an if inside another if.

age = 25
has_id = True

if age >= 18:
    if has_id:
        print("You can enter.")
    else:
        print("You need an ID.")
else:
    print("You are too young.")

Ternary Operator

meaning = 42
print("Greater") if meaning > 10 else print("Lesser")

Using Logical Operators in Conditions

We can combine conditions using and, or, and not.

age = 20
country = "Bangladesh"

if age >= 18 and country == "Bangladesh":
    print("You can vote in Bangladesh.")

User Input

In Python, we use the built-in function: input()

name = input("Enter your name: ")
print("Hello,", name)

# Integer Input
age = int(input("Enter your age: "))
print("You are", age, "years old.")

#Float Input (for decimals)
price = float(input("Enter the price: "))
print("The price is", price)

You can take multiple values using split()

x, y = input("Enter two numbers separated by space: ").split()
x = int(x)
y = int(y)
print("Sum:", x + y)

Python Lists

Lists are ordered, changeable collections.
They can hold different data types — numbers, strings, even other lists.

fruits = ["apple", "banana", "cherry"]
print(fruits)

# Accessing Items
print(fruits[0])  # First item
print(fruits[-1]) # Last item
print(fruits[2:2])

# Changing Items
fruits[1] = "mango"
print(fruits)

# Adding Items
fruits.append("orange")     # Add at end
fruits.insert(1, "grape")   # Add at position 1

# Removing Items
fruits.remove("apple")  # Remove by value
fruits.pop(0)           # Remove by index
fruits.clear()          # Remove all items

# Loop Through a List
for fruit in fruits:
    print(fruit)

# List Functions
len(fruits)           # Length
fruits.sort()         # Sort alphabetically
fruits.reverse()      # Reverse order
fruits.count("apple") # Count occurrences
del fruits[0]         # Delete the first item on the list

Python Tuples

Tuples are ordered but immutable —
you can’t change or remove items once created.

colors = ("red", "green", "blue")
print(colors)
print(colors[0])
print(colors[-1])

# Tuple Operations
t = (10, 20, 30)
print(len(t))
print(max(t))
print(min(t))
print(sum(t))

# Tuple Unpacking
person = ("Manan", 24, "Bangladesh")
name, age, country = person
print(name, age, country)

Python Dictionaries

A dictionary in Python is a collection of key–value pairs.
Each key is unique and maps to a value.

Think of it like a mini database or a real dictionary:

person = {
    "name": "Manan Ahmed",
    "age": 24,
    "profession": "Photographer"
}

person2 = dict(name="Broti", age=27, height="5 feet 6", weight="75kg")

print(person)
print(person2.keys())
print(person2.values())
print("name2" in person2)

print(person["name"])         # Using key
print(person.get("profession"))  # Using get(). get() is safer — it doesn’t crash if the key doesn’t exist.

# Changing or Adding Items
person["age"] = 25              # Change value
person["country"] = "Bangladesh" # Add new key-value pair
person2.update(Degree="Ahmed")
print(person)

# Removing Items
person.pop("profession")   # Remove by key
person.popitem()           # Remove last added item
del person["age"]          # Delete specific key
person.clear()             # Remove all items

# Using Loops
for key, value in person.items():
    print(key, ":", value)

# Nested Dictionary
students = {
    "student1": {"name": "Jhon", "age": 20},
    "student2": {"name": "Rebeca", "age": 21}
}

print(students["student1"]["name"])  # Output: Jhon

# Dictionary Copy
person = person2.copy() # ✅ Copy
person = dict(person2)  # ✅ dict() constructor, another way to copy

person = person # ❌ Bad Copy, works as a reference 

Python Sets

A set is a collection of unique items —
it automatically removes duplicates and is unordered (items have no fixed position).

fruits = {"apple", "banana", "cherry"}
print(fruits)

# Output Could be: {'banana', 'apple', 'cherry'} 
# ⚠️ The order may change — sets are unordered.

Empty Set : must use set(), not {}, because {} makes an empty dictionary.

empty_set = set()
print(type(empty_set))  # <class 'set'>

Duplicates Are Not Allowed in sets

nums = {1, 2, 2, 3, 3, 3}
print(nums)

# Output: {1, 2, 3}

Add, Update and Remove Items

fruits = {"apple", "banana"}
fruits.add("cherry")           # Add one item
fruits.update(["mango", "grape"])  # Add multiple items
print(fruits)

fruits.remove("banana")   # Removes item; error if not found
fruits.discard("orange")  # Removes item; no error if not found
fruits.pop()              # Removes a random item
fruits.clear()            # Removes all items

Set Operations

Sets are great for math-like operations.
Let’s Try:

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
OperationSymbol / MethodExampleResult
Union (combine all)`ABorA.union(B)`{1,2,3,4,5,6}
Intersection (common items)A & B or A.intersection(B){3,4}
Difference (items in A not in B)A - B or A.difference(B){1,2}
Symmetric Difference (items not common)A ^ B or A.symmetric_difference(B){1,2,5,6}

Membership Test

print(2 in A)     # True
print(5 not in A) # True

for item in A:
    print(item)

Set Methods

MethodDescription
.add()Add one element
.update()Add multiple elements
.remove()Remove element (error if missing)
.discard()Remove element (no error if missing)
.clear()Remove all items
.union()Combine two sets
.intersection()Common elements
.difference()Elements in one but not other
.symmetric_difference()Elements not common

Summary

PropertyDescription
Ordered❌ No
Duplicates❌ Not allowed
Mutable✅ Yes
Indexing❌ Not supported
Useful forUnique collections, fast membership tests

Python Loops

Python has two main types of loops:

  • for loop
  • while loop

for Loop

Basic Example

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

Loop through a list

fruits = ["apple", "banana", "mango"]

for fruit in fruits:
    print(fruit)

Loop through a string

for char in "Python":
    print(char)

Loop with custom range

for i in range(1, 11, 2):
    print(i)

''' Here:

1 → start

11 → stop (not included)

2 → step size '''

while Loop

Basic Example:

i = 1

while i <= 5:
    print(i)
    i += 1

loop Controls

break → stop the loop

for i in range(10):
    if i == 5:
        break
    print(i)

continue → skip the current iteration

for i in range(10):
    if i == 5:
        continue
    print(i)

pass → placeholder, does nothing

for i in range(5):
    pass

Nested Loops (Loop inside a loop)

for i in range(3):
    for j in range(2):
        print(i, j)

⚠️ Important

Make sure the condition will become False, otherwise the loop will run forever.

Function

A function is a reusable block of code that performs a specific task.

Example Syntax:

def function_name():
    # code

def greet():
    print("Hello, welcome to Python!")

Calling the function:

greet()

Parameters allow you to pass data into a function. Function with Parameters example:

def greet(name):
    print("Hello", name)

greet("Manan")
greet("Ahmed")

A function can return a result using return. Example:

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

result = add(5, 3)
print(result)

A function can have multiple parameters. Example:

def student_info(name, age, city):
    print("Name:", name)
    print("Age:", age)
    print("City:", city)

student_info("Manan", 24, "Dhaka")

Default parameter value example:

def greet(name="Guest"):
    print("Hello", name)

greet()
greet("Manan")

A function can use Keyword Arguments. You can pass arguments by name. Example:

def login(username, password):
    print(username, password)
login(password="1234", username="admin")

Used when you don’t know how many arguments will be passed you can use Arbitrary Arguments (*args)

def add_numbers(*nums):
    total = 0
    for n in nums:
        total += n
    return total

print(add_numbers(1, 2, 3, 4))

Arbitrary Keyword Arguments (**kwargs) Example:

def profile(**info):
    for key, value in info.items():
        print(key, ":", value)

profile(name="Manan", age=24, country="Bangladesh")

Local and Global Variables example in fuction:

x = 10  # Global

def my_func():
    x = 5  # Local
    print(x)

my_func()
print(x)

Example Program:

def calculator(a, b, op):
    if op == "+":
        return a + b
    elif op == "-":
        return a - b
    elif op == "*":
        return a * b
    elif op == "/":
        return a / b
    else:
        return "Invalid operator"

print(calculator(10, 5, "+"))

Lambda & Higher Order Functions

Lambda Functions

A lambda function is a small anonymous function (no name).

Syntax:

lambda arguments : expression

✔️ Can have any number of arguments
❌ Only one expression (no statements)

Normal function vs lambda function example:

# Normal Function
def square(x):
    return x * x

# Basic Lambda Function
square = lambda x: x * x
print(square(5))

# Lambda Function with Multiple Arguments
add = lambda a, b: a + b
print(add(10, 20))

# Lambda Function with Condition
check_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check_even(7))

Higher-Order Functions

A higher-order function is a function that:

  • takes another function as an argument OR
  • returns a function

Example:

# Function as Argument
def greet(func):
    func()

def say_hello():
    print("Hello!")

greet(say_hello)

# Function Returning Function
def multiplier(n):
    return lambda x: x * n

double = multiplier(2)
print(double(5))

Classes & Objects

What is a Class?

A class is a blueprint/template for creating objects.

It defines:

  • properties (variables)
  • behaviors (functions)

What is an Object?

An object is a real instance of a class. If Class = Blueprint, then Object = Actual thing

Example of creating a class:

class Person:
    pass

Class with Attributes & Methods Example:

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

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

Example of creating objects:

p1 = Person("Manan", 24)
p2 = Person("Ahmed", 22)

p1.greet()
p2.greet()

The __init__() Method

  • Called automatically when an object is created
  • Used to initialize object data

Example:

def __init__(self, name, age):
    self.name = name
    self.age = age

self Keyword:

  • Refers to the current object
  • Used to access variables & methods of the class

Modifying Object Properties example:

p1.age = 25
print(p1.age)

Deleting Properties or Objects example:

del p1.age
del p1

OOP Basics

Inheritance

One class inherits properties & methods from another.

class Student(Person):
    def __init__(self, name, age, roll):
        super().__init__(name, age)
        self.roll = roll

    def info(self):
        print(self.name, self.age, self.roll)
s1 = Student("Manan", 24, 101)
s1.info()

Polymorphism

Same method name, different behavior. Example:

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

class Dog(Bird):
    def sound(self):
        print("Dog barks")

Encapsulation

Restrict access to data.

class Account:
    def __init__(self):
        self.__balance = 0   # private variable

    def deposit(self, amount):
        self.__balance += amount