Python Cheat Sheet for Beginners
Python Cheat Sheet for Beginners

Welcome to the world of Python! This article is all about “Python Cheat Sheet for Beginners (2023),” which is a beginner-friendly cheat sheet guide that will help you embark on your coding journey with this powerful programming language. Python is renowned for its simplicity, efficiency, and versatility, making it an excellent choice for both scripting and application development across multiple platforms.

This is a comprehensive guide to learning Python through practical examples. This article aims to simplify the process of understanding Python programming by providing step-by-step tutorials and real-world code samples. Whether you’re a beginner or looking to expand your Python skills, this tutorial offers clear explanations and hands-on exercises to help you grasp the fundamentals of Python coding. Feel free to explore these various concepts and showcase practical examples to enhance your understanding and proficiency in Python programming.

Table of Contents

Introduction to Python with Simple Calculator Example


# Constant Values
num1 = 10
num2 = 5

# Addition Operator
addition = num1 + num2

# Subtraction Operator
subtraction = num1 - num2

# Multiplication Operator
multiplication = num1 * num2

# Division Operator
division = num1 / num2

# Displaying the results
print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)

Output:


Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0

Advanced Calculator Example


# Function to add two numbers
def add(a, b):
    return a + b

# Function to subtract two numbers
def subtract(a, b):
    return a - b

# Function to multiply two numbers
def multiply(a, b):
    return a * b

# Function to divide two numbers
def divide(a, b):
    return a / b

# User interface
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

operation = input("Choose an operation (+, -, *, /): ")

result = 0

if operation == "+":
    result = add(num1, num2)
elif operation == "-":
    result = subtract(num1, num2)
elif operation == "*":
    result = multiply(num1, num2)
elif operation == "/":
    result = divide(num1, num2)

print("The result is:", result)

Output:


Enter the first number: 6
Enter the second number: 7
Choose an operation (+, -, *, /): -
The result is: -1.0

Python Numbers: Example


# Integer Example
x = 10
y = 5

# Addition Operator
addition = x + y
print("Addition:", addition)

# Subtraction Operator
subtraction = x - y
print("Subtraction:", subtraction)

# Multiplication Operator
multiplication = x * y
print("Multiplication:", multiplication)

# Division Operator
division = x / y
print("Division:", division)


# Float Example
a = 3.14
b = 2.5

# Addition Operator
addition_float = a + b
print("Float Addition:", addition_float)

# Subtraction Operator
subtraction_float = a - b
print("Float Subtraction:", subtraction_float)

# Multiplication Operator
multiplication_float = a * b
print("Float Multiplication:", multiplication_float)

# Division Operator
division_float = a / b
print("Float Division:", division_float)

Output:


Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Float Addition: 5.640000000000001
Float Subtraction: 0.6400000000000001
Float Multiplication: 7.8500000000000005
Float Division: 1.256

Python String: Example


# Creating a String and store in a variable
greeting = "Hello, World!"
print(greeting)

# Concatenating or combining multiple Strings
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print("Full Name:", full_name)

# Accessing Individual Characters in a string
message = "Python is fun!"
print("First Character:", message[0])
print("Last Character:", message[-1])

# Knowing the String Length
length = len(message)
print("Length:", length)

# String Slicing Practice
substring = message[7:9]
print("Substring:", substring)

# Modifying Strings into capital format
name = "john doe"
capitalized_name = name.capitalize()
print("Capitalized Name:", capitalized_name)

# String Formatting practice
age = 25
job = "Engineer"
message = "I am {} years old and work as an {}.".format(age, job)
print(message)

Output:


Hello, World!
Full Name: John Doe
First Character: P
Last Character: !
Length: 14
Substring: is
Capitalized Name: John doe
I am 25 years old and work as an Engineer.

Python Lists: Example


# Creating a List
cars = ["sedan", "SUV", "hatchback", "convertible"]
print(cars)

# Accessing List Items
print("First Car Type:", cars[0])
print("Last Car Type:", cars[-1])

# Modifying List Items
cars[1] = "pickup truck"
print("Modified List:", cars)

# List Length
length = len(cars)
print("Length:", length)

# Adding Items to a List
cars.append("minivan")
print("Updated List:", cars)

# Removing Items from a List
removed_car = cars.pop(2)
print("Removed Car Type:", removed_car)
print("Updated List:", cars)

# Slicing a List
subset = cars[1:3]
print("Subset:", subset)

# List Concatenation
more_cars = ["sports car", "electric car"]
all_cars = cars + more_cars
print("All Cars:", all_cars)

Output:


['sedan', 'SUV', 'hatchback', 'convertible']
First Car Type: sedan
Last Car Type: convertible
Modified List: ['sedan', 'pickup truck', 'hatchback', 'convertible']
Length: 4
Updated List: ['sedan', 'pickup truck', 'hatchback', 'convertible', 'minivan']
Removed Car Type: hatchback
Updated List: ['sedan', 'pickup truck', 'convertible', 'minivan']
Subset: ['pickup truck', 'convertible']
All Cars: ['sedan', 'pickup truck', 'convertible', 'minivan', 'sports car', 'electric car']

Some of Lists Methods


# Using Lists as Stacks
stack = [3, 4, 5]
stack.append(6)
stack.pop()
print(stack)    # Output: [3, 4, 5]

# Using Lists as Queues
queue = [3, 4, 5]
queue.append(6)
queue.pop(0)
print(queue)    # Output: [4, 5, 6]

Output:


[3, 4, 5]
[4, 5, 6]

List Comprehensions


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

Output:


[1, 4, 9, 16, 25]

Nested List Comprehensions


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

Output:


[1, 2, 3, 4, 5, 6, 7, 8, 9]

Python Sets: Example


# Creating a Set
luxury_cars = {"Mercedes", "BMW", "Audi", "Lamborghini"}
print(luxury_cars)

# Adding Elements to a Set
luxury_cars.add("Rolls-Royce")
print("Updated Set:", luxury_cars)

# Removing Elements from a Set
luxury_cars.remove("BMW")
print("Updated Set:", luxury_cars)

# Set Operations
sports_cars = {"Ferrari", "Lamborghini", "Porsche", "Bugatti"}

# Union
union_set = luxury_cars.union(sports_cars)
print("Union Set:", union_set)

# Intersection
intersection_set = luxury_cars.intersection(sports_cars)
print("Intersection Set:", intersection_set)

# Difference
difference_set = luxury_cars.difference(sports_cars)
print("Difference Set:", difference_set)

Output:


{'Mercedes', 'BMW', 'Audi', 'Lamborghini'}
Updated Set: {'Mercedes', 'Audi', 'Lamborghini', 'BMW', 'Rolls-Royce'}
Updated Set: {'Mercedes', 'Audi', 'Lamborghini', 'Rolls-Royce'}
Union Set: {'Ferrari', 'Bugatti', 'Mercedes', 'Audi', 'Porsche', 'Lamborghini', 'Rolls-Royce'}
Intersection Set: {'Lamborghini'}
Difference Set: {'Mercedes', 'Audi', 'Rolls-Royce'}

Python Tuple: Example


# Creating a Tuple
car1 = ("BMW", "X5", 2022)
car2 = ("Mercedes", "E-Class", 2021)
car3 = ("Audi", "Q7", 2023)

# Accessing Tuple Items
print("Car 1:", car1)
print("Car 2:", car2)
print("Car 3:", car3)

# Accessing Individual Elements
print("Car 1 - Make:", car1[0])
print("Car 2 - Model:", car2[1])
print("Car 3 - Year:", car3[2])

# Tuple Length
print("Number of Cars:", len(car1))

# Looping Through a Tuple
print("All Cars:")
for car in (car1, car2, car3):
    print(car)

# Combining Tuples
all_cars = car1 + car2 + car3
print("All Cars:", all_cars)

Output:


Car 1: ('BMW', 'X5', 2022)
Car 2: ('Mercedes', 'E-Class', 2021)
Car 3: ('Audi', 'Q7', 2023)
Car 1 - Make: BMW
Car 2 - Model: E-Class
Car 3 - Year: 2023
Number of Cars: 3
All Cars:
('BMW', 'X5', 2022)
('Mercedes', 'E-Class', 2021)
('Audi', 'Q7', 2023)
All Cars: ('BMW', 'X5', 2022, 'Mercedes', 'E-Class', 2021, 'Audi', 'Q7', 2023)

Python Dictionaries: Example


# Creating a Dictionary
car1 = {"make": "BMW", "model": "X5", "year": 2022}
car2 = {"make": "Mercedes", "model": "E-Class", "year": 2021}
car3 = {"make": "Audi", "model": "Q7", "year": 2023}

# Accessing Dictionary Items
print("Car 1:", car1)
print("Car 2:", car2)
print("Car 3:", car3)

# Accessing Individual Values
print("Car 1 - Make:", car1["make"])
print("Car 2 - Model:", car2["model"])
print("Car 3 - Year:", car3["year"])

# Modifying Dictionary Values
car1["year"] = 2023
print("Modified Car 1:", car1)

# Dictionary Length
print("Number of Cars:", len(car1))

# Looping Through a Dictionary
print("All Cars:")
for car in [car1, car2, car3]:
    print(car)

# Adding New Key-Value Pairs
car1["color"] = "black"
print("Updated Car 1:", car1)

# Removing Key-Value Pairs
del car2["model"]
print("Updated Car 2:", car2)

Output:


Car 1: {'make': 'BMW', 'model': 'X5', 'year': 2022}
Car 2: {'make': 'Mercedes', 'model': 'E-Class', 'year': 2021}
Car 3: {'make': 'Audi', 'model': 'Q7', 'year': 2023}
Car 1 - Make: BMW
Car 2 - Model: E-Class
Car 3 - Year: 2023
Modified Car 1: {'make': 'BMW', 'model': 'X5', 'year': 2023}
Number of Cars: 3
All Cars:
{'make': 'BMW', 'model': 'X5', 'year': 2023}
{'make': 'Mercedes', 'model': 'E-Class', 'year': 2021}
{'make': 'Audi', 'model': 'Q7', 'year': 2023}
Updated Car 1: {'make': 'BMW', 'model': 'X5', 'year': 2023, 'color': 'black'}
Updated Car 2: {'make': 'Mercedes', 'year': 2021}

Nested Dictionaries: Creating a nested dictionary


student_scores = {
    "Alice": {"Math": 85, "Science": 90, "English": 92},
    "Bob": {"Math": 78, "Science": 85, "English": 80},
    "Charlie": {"Math": 92, "Science": 88, "English": 95}
}

Nested Dictionaries: Accessing values in a nested dictionary


student_scores = {
    "Alice": {"Math": 85, "Science": 90, "English": 92},
    "Bob": {"Math": 78, "Science": 85, "English": 80},
    "Charlie": {"Math": 92, "Science": 88, "English": 95}
}

print(student_scores["Alice"]["Math"])  # Output: 85
print(student_scores["Bob"]["Science"])  # Output: 85
print(student_scores["Charlie"]["English"])  # Output: 95

Output:


85
85
95

Nested Dictionaries: Modifying values in a nested dictionary


student_scores = {
    "Alice": {"Math": 85, "Science": 90, "English": 92},
    "Bob": {"Math": 78, "Science": 85, "English": 80},
    "Charlie": {"Math": 92, "Science": 88, "English": 95}
}

student_scores["Bob"]["English"] = 88
student_scores["Charlie"]["Science"] = 92

print(student_scores["Bob"]["English"])  # Output: 88
print(student_scores["Charlie"]["Science"])  # Output: 92

Output:


88
92

Nested Dictionaries: Update Nested Dictionary


student_scores = {
    "Alice": {"Math": 85, "Science": 90, "English": 92},
    "Bob": {"Math": 78, "Science": 85, "English": 80},
    "Charlie": {"Math": 92, "Science": 88, "English": 95}
}

# Update values in a nested dictionary
student_scores["Bob"].update({"Math": 80, "English": 85})

# Add a new subject and score for a student
student_scores["Alice"].update({"History": 88})

# Display the updated nested dictionary
print(student_scores)

Output:


{'Alice': {'Math': 85, 'Science': 90, 'English': 92, 'History': 88}, 'Bob': {'Math': 80, 'Science': 85, 'English': 85}, 'Charlie': {'Math': 92, 'Science': 88, 'English': 95}}

Looping Dictionaries: Looping through key-value pairs


person = {"name": "John", "age": 30, "city": "New York"}

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

Output:


name : John
age : 30
city : New York

Looping Dictionaries: Looping through keys


person = {"name": "John", "age": 30, "city": "New York"}

for key in person:
    print(key)

Output:


name
age
city

Looping Dictionaries: Looping through values


person = {"name": "John", "age": 30, "city": "New York"}

for value in person.values():
    print(value)

Output:


John
30
New York

Looping Dictionaries: Looping through sorted keys


person = {"name": "John", "age": 30, "city": "New York"}

for key in sorted(person):
    print(key, ":", person[key])

Output:


age : 30
city : New York
name : John

Looping Dictionaries: Looping through Unique Elements in Sorted Order


fruit_counts = {"apple": 5, "banana": 3, "orange": 2, "grape": 4}

unique_fruits = sorted(set(fruit_counts.keys()))

for fruit in unique_fruits:
    count = fruit_counts[fruit]
    print(fruit, ":", count)

Output:


apple : 5
banana : 3
grape : 4
orange : 2

Looping Nested Dictionaries: Looping through all key-value pairs in a nested dictionary


student_scores = {
    "Alice": {"Math": 85, "Science": 90, "English": 92},
    "Bob": {"Math": 78, "Science": 85, "English": 80},
    "Charlie": {"Math": 92, "Science": 88, "English": 95}
}

for student, scores in student_scores.items():
    for subject, score in scores.items():
        print(student, "scored", score, "in", subject)

Output:


Alice scored 85 in Math
Alice scored 90 in Science
Alice scored 92 in English
Bob scored 78 in Math
Bob scored 85 in Science
Bob scored 80 in English
Charlie scored 92 in Math
Charlie scored 88 in Science
Charlie scored 95 in English

Looping Nested Dictionaries: Looping through Unique Elements in Nested Dictionaries


student_scores = {
    "Alice": {"Math": 85, "Science": 90, "English": 92},
    "Bob": {"Math": 78, "Science": 85, "English": 80},
    "Charlie": {"Math": 92, "Science": 88, "English": 95}
}

unique_subjects = set()

for scores in student_scores.values():
    unique_subjects.update(scores.keys())

for subject in unique_subjects:
    print("Subject:", subject)
    for student, scores in student_scores.items():
        if subject in scores:
            print(student, "scored", scores[subject], "in", subject)

Output:


Subject: Science
Alice scored 90 in Science
Bob scored 85 in Science
Charlie scored 88 in Science
Subject: Math
Alice scored 85 in Math
Bob scored 78 in Math
Charlie scored 92 in Math
Subject: English
Alice scored 92 in English
Bob scored 80 in English
Charlie scored 95 in English

The del statement

Deleting an object


name = "John"
del name
print(name)  # Raises NameError: name 'name' is not defined

Output:


NameError: name 'name' is not defined

Deleting an element from a list


numbers = [1, 2, 3, 4, 5]
del numbers[2]
print(numbers)  # Output: [1, 2, 4, 5]

Output:


[1, 2, 4, 5]

Deleting a key-value pair from a dictionary


person = {"name": "John", "age": 30, "city": "New York"}
del person["age"]
print(person)  # Output: {'name': 'John', 'city': 'New York'}

Output:


{'name': 'John', 'city': 'New York'}

Deleting multiple objects or elements


a = 1
b = 2
c = 3

del a, b, c

numbers = [1, 2, 3, 4, 5]
del numbers[1:4]
print(numbers)  # Output: [1, 5]

Output:


[1, 5]

Python If …… Else Statement: Example



# Example: Checking if a number is positive or negative

number = 10

if number >= 0:
    print("The number is positive.")
else:
    print("The number is negative.")

# Example: Checking if a user is eligible for voting

age = 18

if age >= 18:
    print("You are eligible to vote!")
else:
    print("You are not eligible to vote yet.")

# Example: Checking if a number is even or odd

number = 7

if number % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")

Output:


The number is positive.
You are eligible to vote!
The number is odd.

Python While Loops Statement: Example


# Example: Printing numbers from 1 to 5 using a while loop
counter = 1
while counter <= 5:
    print(counter)
    counter += 1
# Example: Calculating the sum of numbers from 1 to 10 using a while loop
sum = 0
num = 1
while num <= 10:
    sum += num
    num += 1
print("The sum of numbers from 1 to 10 is:", sum)

Output:


1
2
3
4
5
The sum of numbers from 1 to 10 is: 55

Printing numbers in reverse order using a while loop


counter = 10

while counter >= 1:
    print(counter)
    counter -= 1

Output:


10
9
8
7
6
5
4
3
2
1

Computing the factorial of a number using a while loop


number = 5
factorial = 1

while number > 0:
    factorial *= number
    number -= 1

print("The factorial of 5 is:", factorial)

Output:


The factorial of 5 is: 120

Reversing a string using a while loop


text = "Hello, World!"
reversed_text = ""

index = len(text) - 1

while index >= 0:
    reversed_text += text[index]
    index -= 1

print("Reversed Text:", reversed_text)

Output:


Reversed Text: !dlroW ,olleH

Python For Loops: Example


# Printing numbers from 1 to 5 using a for loop

for number in [1, 2, 3, 4, 5]:
    print(number)

Output:


1
2
3
4
5

Iterating over a list of cars


cars = ["BMW", "Mercedes", "Audi", "Toyota"]

for car in cars:
    print(car)

Output:


BMW
Mercedes
Audi
Toyota

Iterating over characters in a String


model = "Camry"

for character in model:
    print(character)

Output:


C
a
m
r
y

Iterating over a range of years


for year in range(2010, 2023):
    print(year)

Output:


2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022

Skipping iterations using continue Statement


prices = [10000, 15000, 20000, 25000, 30000]

for price in prices:
    if price > 20000:
        continue
    print(price)

Output:


10000
15000
20000

Terminating the loop using break Statement


brands = ["BMW", "Mercedes", "Audi", "Toyota", "Lexus"]

for brand in brands:
    if brand == "Audi":
        break
    print(brand)

Output:


BMW
Mercedes

Pass Statement


print("This block is intentionally left empty")
if 5 > 2:
    pass  # This block is intentionally left empty

Output:


This block is intentionally left empty

Match Statements:


# Available from Python 3.10
value = 3
match value:
    case 1:
        print("One")
    case 2:
        print("Two")
    case _:
        print("Other")

Output:


Other

The range() Function: Example


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

Output:


0
1
2
3
4

Python Functions: Example

Creating and calling a simple function


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

greet()

Output:


Hello, welcome to Python!

Function with parameters and return value


def add_numbers(num1, num2):
    sum = num1 + num2
    return sum

result = add_numbers(10, 5)
print("The sum is:", result)

Output:


The sum is: 15

Recursive function


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

result = factorial(5)
print("The factorial is:", result)

Output:


The factorial is: 120

Default parameter value


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

greet()  # Output: Hello, Guest
greet("John")  # Output: Hello, John

Output:


Hello, Guest
Hello, John

Special parameters: Examples

Positional-or-Keyword Arguments


def multiply(a, b, c=None):
    if c:
        return a * b * c
    else:
        return a * b

print(multiply(2, 3))        # Output: 6
print(multiply(2, 3, 4))     # Output: 24

Output:


6
24

Positional-Only Parameters


# Available from Python 3.8
def my_func(a, b, /, c, d, *, e, f):
    print(a, b, c, d, e, f)

my_func(1, 2, 3, 4, e=5, f=6)

Output:


1 2 3 4 5 6

Keyword-Only Arguments


# Available from Python 3.0
def greet(*, name):
    print("Hello, " + name)

greet(name="Alice")

Output:


Hello, Alice

Arbitrary Argument Lists


def add(*numbers):
    total = 0
    for number in numbers:
        total += number
    return total

result = add(1, 2, 3, 4, 5)
print(result)    # Output: 15

Output:


15

Unpacking Argument Lists


def multiply(a, b, c):
    return a * b * c

numbers = [2, 3, 4]
result = multiply(*numbers)
print(result)    # Output: 24

Output:


24

Lambda function


multiply = lambda x, y: x * y

result = multiply(5, 3)
print("The result is:", result)

Output:


The result is: 15

Documentation Strings


def square(x):
    """Return the square of a number."""
    return x ** 2

print(square.__doc__)    # Output: Return the square of a number.

Output:


Return the square of a number.

Function Annotations


def greet(name: str) -> None:
    print("Hello, " + name)

greet("Alice")

Output:


Hello, Alice

Python Arrays: Example

Creating and accessing an array


import array as arr

numbers = arr.array('i', [1, 2, 3, 4, 5])

print("Array elements:")
for number in numbers:
    print(number)

print("Accessing an element:")
print(numbers[2])

Output:


Array elements:
1
2
3
4
5
Accessing an element:
3

Modifying array elements


import array as arr

numbers = arr.array('i', [1, 2, 3, 4, 5])

print("Original array:")
for number in numbers:
    print(number)

numbers[2] = 10

print("Modified array:")
for number in numbers:
    print(number)

Output:


Original array:
1
2
3
4
5
Modified array:
1
2
10
4
5

Array operations


import array as arr

numbers1 = arr.array('i', [1, 2, 3])
numbers2 = arr.array('i', [4, 5, 6])

concatenated = numbers1 + numbers2
repeated = numbers1 * 2

print("Concatenated array:")
for number in concatenated:
    print(number)

print("Repeated array:")
for number in repeated:
    print(number)

Output:


Concatenated array:
1
2
3
4
5
6
Repeated array:
1
2
3
1
2
3

Array methods


import array as arr

numbers = arr.array('i', [1, 2, 3, 4, 5])

print("Original array:")
for number in numbers:
    print(number)

numbers.append(6)
numbers.insert(2, 7)
numbers.pop()

print("Modified array:")
for number in numbers:
    print(number)

Output:


Original array:
1
2
3
4
5
Modified array:
1
2
7
3
4
5

Summary

The provided cheat sheet for Python beginners covers various fundamental aspects of Python programming. It begins with a simple example of Python code. The cheat sheet then dives into key topics such as numbers, strings, and lists, providing examples and explanations for better understanding.

The cheat sheet also covers control flow tools, including if statements, for loops, and functions.

In summary, this cheat sheet serves as a concise guide for beginners to explore Python's core concepts, data structures, control flow, functions, and many more.

In the future, it will cover the concept of modules and we aim to provide insights into input/output operations. Error handling, classes, and object-oriented programming are also planned to explain in the near future tutorials, along with an overview of the Python Standard Library and virtual environments.

Categorized in: