Python Cheat Sheet: Full Guide

Python Cheat Sheet: Full Guide

17 Jul 2025
Beginner
19 Views
42 min read
Learn with an interactive course and practical hands-on labs

Free Python Programming Course For Beginners

A Python cheat sheet offers a quick reference for key syntax, concepts, and commands to help developers write efficient code without memorizing everything.

Python is one of the most beginner-friendly and powerful programming languages used in web development, data science, automation, artificial intelligence, and more.In this Python Cheat Sheet you will understand and get into flow of Python. You will meet every concepts of python with structured way.

python cheat sheet

Step 1: Python Basics

1. Variables and Data Types

Variable:Variable in Python is a name used to store data. Python is dynamically typed, so you don’t need to declare the data type explicitly.

Example:

name = "Alice"        # string
age = 25              # integer
height = 5.4          # float
is_student = True     # boolean 

Common Data Types:

Data TypeDescriptionExample
intWhole numbersx = 10
floatDecimal numberspi = 3.14
strText stringsname = "Bob"
boolBoolean (True/False)is_valid = False

Checking the Data Type:

x = 25
print(type(x))  # <class 'int'> 

2. Comments

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

Single-line Comment:

# This is a single-line comment
print("Hello")  # Comment at the end 

Multi-line Comment:

"""
This is a multi-line comment
Used for documentation or explanation
""" 

3. Type Casting

Type Casting means converting the data type of a value from one type to another using built-in functions.

Common Conversion Functions:

FunctionPurposeExample
int()Convert to integerint("5") → 5
float()Convert to floatfloat("3.2") → 3.2
str()Convert to stringstr(10) → "10"
bool()Convert to booleanbool(1) → True

Examples

x = int("10")
y = float("5.5")
z = str(25)

print(bool(0))   # False
print(bool(5))   # True 

Common Error:

int("hello")  # ValueError: invalid literal for int() 

Step 2: Operators in Python

Operators in Python are symbols used to perform operations on variables and values. Python has a variety of operators for different types of tasks.

Types of Python Operators

Operator TypeDescription
Arithmetic OperatorsPerform basic mathematical operations
Comparison OperatorsCompare two values
Assignment OperatorsAssign values to variables
Logical OperatorsCombine multiple conditions
Identity OperatorsCompare memory location
Membership OperatorsCheck for membership in sequences
Bitwise OperatorsPerform bit-level operations

1. Arithmetic Operators

Used to perform mathematical operations.

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

2. Comparison Operators

Used to compare values and return Boolean results.

OperatorDescriptionExampleResult
==Equal toa == bFalse
!=Not equal toa != bTrue
>Greater thana > bTrue
<Less thana < bFalse
>=Greater than or equala >= bTrue
<=Less than or equala <= bFalse

3. Assignment Operators

Used to assign values and perform shorthand operations.

OperatorDescriptionExampleEquivalent
=Assignx = 5-
+=Add and assignx += 3x = x + 3
-=Subtract and assignx -= 3x = x - 3
*=Multiply and assignx *= 3x = x * 3
/=Divide and assignx /= 3x = x / 3
//=Floor divide and assignx //= 3x = x // 3
%=Modulus and assignx %= 3x = x % 3
**=Power and assignx **= 3x = x ** 3

4. Logical Operators

Used to combine conditional statements.

OperatorDescriptionExampleResult
andTrue if both are trueTrue and FalseFalse
orTrue if at least one is trueTrue or FalseTrue
notInverts the resultnot TrueFalse

5. Identity Operators

Used to compare memory locations (not just values).

OperatorDescriptionExampleResult
isTrue if same objecta is bFalse
is notTrue if different objectsa is not b

True

Example

a = [1, 2]
b = [1, 2]
print(a == b)   # True (same values)
print(a is b)   # False (different memory objects) 

6. Membership Operators

Used to check if a value is part of a sequence.

OperatorDescriptionExampleResult
inTrue if present"a" in "apple"True
not inTrue if not present"z" not in "apple"True

7. Bitwise Operators

Used for binary-level operations.

OperatorDescriptionExampleResult
&AND5 & 31
|OR5 | 37
^XOR5 ^ 36
~NOT~5-6
<<Left Shift5 << 110
>>Right Shift5 >> 12

Step 3: Data Structures

Python provides built-in data structures that are essential for organizing and storing data efficiently. These include both simple and complex structures like Lists, Tuples, Sets, and Dictionaries.

1. List

A list is an ordered, mutable collection that allows duplicate items.

fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # Output: apple
  • Mutable (can change after creation)
  • Supports indexing and slicing
  • Methods: append(), remove(), pop(), sort()

2. Tuple

A tuple is an ordered, immutable collection.

coordinates = (10, 20)
print(coordinates[1])  # Output: 20
  • Immutable (cannot change after creation)
  • Supports indexing
  • Used for fixed data

3. Set

A set is an unordered collection of unique elements.

numbers = {1, 2, 3, 2}
print(numbers)  # Output: {1, 2, 3} 
  • No duplicates allowed
  • Unordered — no indexing
  • Methods: add(), remove(), union(), intersection()

4. Dictionary

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

student = {"name": "Alice", "age": 22}
print(student["name"])  # Output: Alice
  • Keys must be unique and immutable
  • Values can be of any data type
  • Methods: keys(), values(), get(), update()

Comparison Table

Data StructureOrderedMutableAllows DuplicatesIndexed
ListYesYesYesYes
TupleYesNoYesYes
SetNoYesNoNo
DictionaryNo (3.7+ maintains insertion order)YesKeys - No, Values - YesKeys act like index

Step 4: Control Flow

Control flow statements in Python determine the order in which instructions are executed. Python supports the following control flow constructs:

1. Conditional Statements

Used to perform different actions based on different conditions.

if Statement

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

if-else Statement

x = 3
if x > 5:
    print("x is greater than 5")
else:
    print("x is 5 or less") 

if-elif-else Statement

x = 5
if x > 5:
    print("Greater")
elif x == 5:
    print("Equal")
else:
    print("Less") 

2. Loops

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

for Loop

Used for iterating over a sequence (like list, tuple, string).

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

while Loop

Repeats while a condition is true.

count = 0
while count < 3:
    print(count)
    count += 1 

3. Loop Control Statements

These control how loops are executed.

  • break: Exits the loop prematurely.
  • continue: Skips the current iteration and continues with the next one.
  • pass: Does nothing; used as a placeholder.

break Example

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

continue Example

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

pass Example

for i in range(5):
    if i == 2:
        pass
    print(i) 

4. Nested Control Flow

You can nest if-else statements or loops within each other.

for i in range(3):
    if i % 2 == 0:
        print(f"{i} is even")
    else:
        print(f"{i} is odd") 

Step 5: Functions

Python Functions are blocks of reusable code that perform a specific task. They help in modular programming and reduce code redundancy.

1. Defining a Function

Functions are defined using the def keyword followed by the function name and parentheses.

def greet():
    print("Hello, world!") 

2. Calling a Function

Once defined, a function can be called using its name followed by parentheses.

greet() 

3. Function with Parameters

Functions can accept input values, called parameters or arguments.

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

4. Function with Return Value

Functions can return values using the return statement.

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

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

5. Default Parameters

Parameters can have default values which are used if no argument is passed.

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

greet()
greet("Bob") 

6. Keyword Arguments

Arguments can be passed in the form of key=value pairs.

def student_info(name, age):
    print(f"Name: {name}, Age: {age}")

student_info(age=21, name="John") 

7. Variable-Length Arguments

Python allows you to handle functions with an arbitrary number of arguments.

*args (Non-keyword Arguments)

def total(*numbers):
    return sum(numbers)

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

**kwargs (Keyword Arguments)

def print_info(**info):
    for key, value in info.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25) 

8. Lambda Functions

Lambda function in Python are anonymous functions written in a single line using the lambda keyword.

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

9. Nested Functions

Functions defined inside another function.

def outer():
    def inner():
        print("Inside inner function")
    inner()

outer() 

10. Recursion

A function calling itself is known as recursion.

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

print(factorial(5))  # Output: 120 

Step 6: Exception Handling

Exception handling in Python is used to gracefully handle errors that occur during program execution. It prevents the program from crashing and allows custom error responses.

1. What is an Exception?

An exception is an error that occurs during the execution of a program, disrupting the normal flow of instructions.

2. Basic try-except Block

The try block lets you test a block of code for errors. The except block lets you handle the error.

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!") 

3. Catching Multiple Exceptions

try:
    x = int("abc")
except (ValueError, TypeError):
    print("Invalid input!") 

4. Using else with try-except

The else block executes if no exceptions occur.

try:
    x = int("10")
except ValueError:
    print("Conversion failed.")
else:
    print("Conversion successful:", x) 

5. finally Block

The finally block runs no matter what, even if an exception is raised or not.

try:
    f = open("test.txt", "r")
except FileNotFoundError:
    print("File not found.")
finally:
    print("Execution completed.") 

6. Raising Exceptions

You can raise exceptions using the raise keyword.

def divide(a, b):
    if b == 0:
        raise ValueError("Denominator cannot be zero")
    return a / b

print(divide(10, 2)) 

7. Custom Exceptions

You can define your own exception classes by inheriting from the Exception class.

class AgeTooSmallError(Exception):
    pass

age = 12
if age < 18:
    raise AgeTooSmallError("You must be at least 18 years old.") 

8. Common Python Exceptions

  • ZeroDivisionError: Division by zero
  • ValueError: Invalid value
  • TypeError: Invalid type
  • IndexError: Index out of range
  • KeyError: Key not found in dictionary
  • FileNotFoundError: File not found

9. Best Practices

  • Catch specific exceptions instead of a general except.
  • Use finally to release resources.
  • Avoid catching exceptions you can't handle.
  • Document raised exceptions in your functions.
  • Step 7: File Handling

    1. Reading a File

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

    2. Writing to a File

    
    with open("file.txt", "w") as file:
        file.write("Hello, World")
      

    Step 8: Object-Oriented Programming

    Class and Object

    
    class Person:
        def __init__(self, name):
            self.name = name
    
        def greet(self):
            print("Hello", self.name)
    
    p = Person("Alice")
    p.greet()
    

    Step 9: Modules and Packages

    1. Importing Modules

    
    import math
    print(math.sqrt(16))
      

    2. Custom Module

    
    # mymodule.py
    def add(x, y):
        return x + y
      
    
    # usage
    import mymodule
    print(mymodule.add(5, 3))
      

    Step 10: List Comprehension

    List comprehension is a concise way to create lists in Python. It offers a shorter syntax compared to traditional for loops for building new lists by applying an expression to each item in an iterable.

    1. Basic Syntax

    [expression for item in iterable] 

    This creates a new list by evaluating the expression for each item in the iterable.

    Example:

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

    2. With Condition (Filtering)

    [expression for item in iterable if condition] 

    Example:

    even_numbers = [x for x in range(10) if x % 2 == 0]
    print(even_numbers)  # Output: [0, 2, 4, 6, 8] 

    3. With if-else in Expression

    [expression_if_true if condition else expression_if_false for item in iterable] 

    Example:

    labels = ['even' if x % 2 == 0 else 'odd' for x in range(5)]
    print(labels)  # Output: ['even', 'odd', 'even', 'odd', 'even'] 

    4. Nested List Comprehension

    You can use nested list comprehensions to flatten lists or generate combinations.

    matrix = [[1, 2], [3, 4], [5, 6]]
    flattened = [num for row in matrix for num in row]
    print(flattened)  # Output: [1, 2, 3, 4, 5, 6] 

    5. Without List Comprehension (Using Loop)

    # Traditional way
    squares = []
    for x in range(5):
        squares.append(x**2)
    print(squares) 

    List comprehension gives the same result more compactly.

    6. List Comprehension vs Generator Expression

    • List comprehension returns a list in memory.
    • Generator expressions use lazy evaluation and return a generator object.
    # Generator expression
    squares_gen = (x**2 for x in range(5))
    print(next(squares_gen))  # Output: 0 

    7. Use Cases of List Comprehension

    • Creating a list of transformed data
    • Filtering elements
    • Flattening nested lists
    • Extracting specific elements from collections

    8. Best Practices

  • Keep expressions simple for readability.
  • Avoid deeply nested list comprehensions.
  • Use regular loops when logic becomes complex.
  • Step 11: Useful Built-in Functions

    Python provides a rich set of built-in functions that are always available for use without importing any modules. These functions help perform common tasks efficiently.

    1. print()

    Displays output to the console.

    print("Hello, World!") 

    2. len()

    Returns the number of items in an object like list, string, or dictionary.

    len("Python")  # Output: 6 

    3. type()

    Returns the data type of an object.

    type(42)  # Output: <class 'int'> 

    4. input()

    Accepts user input as a string.

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

    5. int(), float(), str()

    Used for type casting (converting between types).

    int("10")     # Output: 10
    float("3.14") # Output: 3.14
    str(25)       # Output: "25" 

    6. sum()

    Returns the sum of all items in an iterable.

    sum([1, 2, 3])  # Output: 6 

    7. max() and min()

    Return the largest and smallest items in an iterable.

    max([1, 9, 4])  # Output: 9
    min([1, 9, 4])  # Output: 1 

    8. sorted()

    Returns a sorted list from an iterable.

    sorted([3, 1, 2])  # Output: [1, 2, 3] 

    9. range()

    Generates a sequence of numbers (used in loops).

    list(range(5))  # Output: [0, 1, 2, 3, 4] 

    10. enumerate()

    Adds a counter to an iterable and returns a tuple (index, value).

    for index, value in enumerate(['a', 'b', 'c']):
        print(index, value) 

    11. zip()

    Combines multiple iterables element-wise into tuples.

    list(zip([1, 2], ['a', 'b']))  # Output: [(1, 'a'), (2, 'b')] 

    12. map()

    Applies a function to each item in an iterable.

    list(map(str.upper, ['python', 'java']))  # Output: ['PYTHON', 'JAVA'] 

    13. filter()

    Filters elements based on a condition (function).

    list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4]))  # Output: [2, 4] 

    14. all() and any()

    • all() returns True if all elements are True.
    • any() returns True if any element is True.
    all([True, True, False])  # Output: False
    any([True, False, False])  # Output: True 

    15. abs()

    Returns the absolute value of a number.

    abs(-7)  # Output: 7 

    16. round()

    Rounds a number to the nearest integer or to the specified decimal places.

    round(3.14159, 2)  # Output: 3.14 

    17. isinstance()

    Checks if an object is an instance of a particular class or type.

    isinstance(5, int)  # Output: True 

    18. eval()

    Parses and evaluates a Python expression from a string.

    eval("2 + 3")  # Output: 5 

    Step 12: Python Virtual Environments

    
    python -m venv env
    source env/bin/activate   # Mac/Linux
    env\Scripts\activate      # Windows
      

    Step 13: Pip Package Installer

    
    pip install numpy
    pip uninstall pandas
    pip list
      

    Step 14: Popular Python Libraries

    PurposeLibrary
    Data Analysispandas, numpy
    Web DevelopmentFlask, Django
    Machine Learningscikit-learn, TensorFlow
    Web ScrapingBeautifulSoup, requests
    Automationselenium, pyautogui
    Visualizationmatplotlib, seaborn
    Read More: Libraries in Python-A Complete Resolution

    Step 15: Debugging Tips

    • Use print statements to debug
    • Use the pdb module: import pdb; pdb.set_trace()
    • Use IDEs like VS Code or PyCharm for built-in debuggers
    Python Roadmap: How to become a Python Developer?
      Conclusion

      This detailed Python cheat sheet covers everything from syntax and data types to functions, loops, OOP, and more. Whether you are a beginner or brushing up your skills, keeping this cheat sheet handy will make you a more confident and efficient Python developer.

      Python is a versatile and beginner-friendly programming language with a wide range of features and capabilities. From basic syntax, variables, and control structures to powerful concepts like list comprehensions, exception handling, and popular libraries, Python provides all the tools necessary for rapid development and problem-solving. Whether you're scripting small tasks, analyzing data, or building full-scale web applications, Python has you covered.  Also if you want to learn free try our Free Python Programming Course its totally worth it. Keep experimenting, keep coding, and enjoy your Python journey!

      FAQs

      Python is a versatile programming language used for a wide array of applications, including web development, software development, data analysis, machine learning, and scripting. Its simple syntax and ease of learning have contributed to its popularity across various industries and for both beginners and experienced programmers

      The @ symbol in Python is used to apply a decorator to a function or method to extend its functionality, or to help perform matrix multiplication

      To begin coding in Python, you'll first need to install Python and a code editor, then learn some basic concepts and practice with simple programs.

      Take our Python skill challenge to evaluate yourself!

      In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

      GET FREE CHALLENGE

      Share Article
      About Author
      Anurag Sinha (Author and Full Stack Developer)

      He is a Full stack developer, and Author. He has more than 8 years of industry expertise on .NET Core, Web API, jQuery, HTML5. He is passionate about learning and sharing new technical stacks.
      Live Training - Book Free Demo
      Azure AI Engineer Certification Training
      22 Jul
      07:00AM - 08:30AM IST
      Checkmark Icon
      Get Job-Ready
      Certification
      Accept cookies & close this