Skip to content
Python Cheat Sheet for Beginners
Back to Blog
Technology & AI10 min read

Python Cheat Sheet for Beginners

G

GoBizly

10 October 2026

Python Cheat Sheet for Beginners: Syntax, Commands & Examples

Python is a popular, general-purpose programming language used in web development, data analysis, artificial intelligence, automation, scripting, and software development.

Its readable syntax makes it a useful starting point for beginners, while its extensive libraries and frameworks support advanced technical applications.

This cheat sheet covers essential Python syntax, variables, data types, operators, conditional statements, loops, functions, collections, error handling, and practical coding examples.

1. What Is Python?

Python is a high-level programming language designed to make code readable and relatively easy to write.

Common Uses of Python

  • Web development.

  • Data analysis and visualization.

  • Artificial intelligence and machine learning.

  • Task automation.

  • Scientific computing.

  • Software testing.

  • API development.

  • File processing and reporting.

Why Learn Python?

  • Readable syntax.

  • Large collection of libraries.

  • Support for multiple programming approaches.

  • Active developer community.

  • Cross-platform availability.

  • Integration with databases, APIs, and other systems.

Python is dynamically typed, meaning variables do not generally require explicit type declarations. It also uses indentation to define code blocks.

2. Your First Python Program

The traditional first program displays a message on the screen.

print("Hello, World!")

Output:

Hello, World!

The print() function displays information.

You can also display numbers and calculations:

print(10)
print(5 + 3)
print("Welcome to Python")

Output:

10
8
Welcome to Python

3. Variables in Python

A variable is a name that refers to a value.

name = "Alex"
age = 25
height = 5.8
is_student = True

In this example:

  • name refers to a string.

  • age refers to an integer.

  • height refers to a floating-point number.

  • is_student refers to a Boolean value.

Variable Naming Rules

  • Names can contain letters, numbers, and underscores.

  • Names cannot begin with a number.

  • Spaces are not allowed.

  • Python keywords cannot be used as variable names.

  • Variable names are case-sensitive.

  • Descriptive names improve readability.

Valid examples:

first_name = "Alex"
total_amount = 1500
item_count = 5

Invalid examples:

# 2name = "Alex"
# first name = "Alex"

Python uses = for assignment. It does not mean the same thing as ==, which checks equality.

4. Python Data Types

Python supports several built-in data types.

Data type

Purpose

Example

int

Whole numbers

25

float

Decimal numbers

3.14

str

Text

"Python"

bool

True or false values

True

list

Ordered, mutable collection

[1, 2, 3]

tuple

Ordered, immutable collection

(1, 2, 3)

set

Collection of unique elements

{1, 2, 3}

dict

Key-value mapping

{"name": "Alex"}

NoneType

Represents the absence of a value

None

Check a Variable's Type

Use type():

age = 25
name = "Alex"

print(type(age))
print(type(name))

Type Conversion

Convert a value when appropriate:

number = int("25")
price = float("19.99")
text = str(100)

Be careful: not every value can be converted successfully.

For example, int("hello") raises a ValueError.

5. Working With Strings

Strings represent text and can be created using single or double quotes.

first_name = "Alex"
message = 'Welcome to Python'

Common String Operations

text = "Python Programming"

print(text.upper())
print(text.lower())
print(text.title())
print(text.replace("Python", "Java"))
print(len(text))

Access Characters

Python uses zero-based indexing.

language = "Python"

print(language[0])   # P
print(language[1])   # y
print(language[-1])  # n

String Slicing

language = "Python"

print(language[0:3])  # Pyt
print(language[2:])   # thon
print(language[:4])   # Pyth

The ending index is excluded.

String Formatting

Use f-strings to insert values into text.

name = "Alex"
age = 25

print(f"My name is {name} and I am {age} years old.")

Output:

My name is Alex and I am 25 years old.

6. Operators in Python

Operators perform calculations, comparisons, and logical operations.

Arithmetic Operators

Operator

Purpose

Example

+

Addition

10 + 5 → 15

-

Subtraction

10 - 5 → 5

*

Multiplication

10 * 5 → 50

/

Division

10 / 5 → 2.0

//

Floor division

11 // 2 → 5

%

Modulus (remainder)

11 % 2 → 1

**

Exponentiation

2 ** 3 → 8

Comparison Operators

x = 10
y = 5

print(x == y)  # False
print(x != y)  # True
print(x > y)   # True
print(x < y)   # False
print(x >= y)  # True
print(x <= y)  # False

Comparison operators return Boolean values.

Logical Operators

age = 25
has_id = True

print(age >= 18 and has_id)
print(age < 18 or has_id)
print(not has_id)
  • and: Both conditions must be true.

  • or: At least one condition must be true.

  • not: Reverses a Boolean condition.

Membership Operators

languages = ["Python", "Java", "SQL"]

print("Python" in languages)
print("C++" not in languages)

Identity Operators

is and is not test whether two references point to the same object.

Use == for value equality in ordinary comparisons. For example, value is None is a common and appropriate identity check.

7. Taking User Input

The input() function reads text entered by the user.

name = input("Enter your name: ")
print(f"Hello, {name}!")

By default, input() returns a string.

Convert the value when you need a number:

age = int(input("Enter your age: "))
print(age + 1)

For decimal input:

price = float(input("Enter the price: "))
print(price)

Invalid numerical input can raise an exception, so real applications should validate user input.

8. Conditional Statements

Conditional statements allow a program to make decisions.

If Statement

age = 20

if age >= 18:
    print("Adult")

If-Else Statement

number = 7

if number % 2 == 0:
    print("Even")
else:
    print("Odd")

If-Elif-Else Statement

marks = 82

if marks >= 90:
    print("Grade A")
elif marks >= 75:
    print("Grade B")
elif marks >= 50:
    print("Grade C")
else:
    print("Needs improvement")

Python checks conditions from top to bottom and executes the first matching branch.

Important: Indentation

Python uses indentation to define blocks.

if True:
    print("This is inside the block")

Incorrect indentation can cause an IndentationError or change the program's behavior.

9. Loops in Python

Loops repeat a block of code.

For Loop

A for loop iterates over an iterable, such as a list or string.

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

Using range()

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

Output: 0, 1, 2, 3, 4

Useful forms:

range(5)        # 0 to 4
range(1, 6)     # 1 to 5
range(0, 10, 2) # 0, 2, 4, 6, 8

The stop value is excluded.

While Loop

A while loop continues as long as its condition is true.

count = 1

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

Make sure the condition can eventually become false to avoid an unintended infinite loop.

Break and Continue

break stops the loop.

continue skips the rest of the current iteration and moves to the next one.

for number in range(1, 6):
    if number == 3:
        continue
    print(number)

Output: 1, 2, 4, 5

10. Python Collections

Collections allow you to store and organize multiple values.

Lists

Lists are ordered and mutable.

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

fruits.append("mango")
fruits.remove("banana")

print(fruits)
print(fruits[0])

Common methods:

  • append(): Add an item at the end.

  • insert(): Insert an item at a specified position.

  • remove(): Remove the first matching value.

  • pop(): Remove and return an item.

  • sort(): Sort the list in place.

  • reverse(): Reverse the list in place.

Tuples

Tuples are ordered and cannot be modified after creation.

coordinates = (10, 20)

print(coordinates[0])

Tuples are useful when you want a fixed collection of values.

Sets

Sets store unique elements.

numbers = {1, 2, 2, 3}

print(numbers)

The duplicate 2 is stored only once. Sets do not guarantee ordinary positional indexing.

Useful methods include add(), remove(), and discard().

Dictionaries

Dictionaries store key-value pairs.

student = {
    "name": "Alex",
    "age": 21,
    "course": "Python"
}

print(student["name"])
print(student.get("age"))

Update a value:

student["age"] = 22
student["city"] = "Hyderabad"

Use get() when you want to retrieve a value without raising a KeyError if the key is missing.

11. Functions in Python

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

Define a Function

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

Functions With Parameters

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

greet("Alex")

Functions With Return Values

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

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

return sends a result back to the caller. It is different from print(), which displays a value.

Default Parameters

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

print(greet())
print(greet("Alex"))

Lambda Functions

A lambda creates a small anonymous function.

square = lambda x: x * x
print(square(5))

For more complex logic, a regular def function is usually easier to read.

12. List Comprehensions

List comprehensions provide a concise way to build lists.

Traditional approach:

squares = []

for number in range(1, 6):
    squares.append(number ** 2)

Using a list comprehension:

squares = [number ** 2 for number in range(1, 6)]

print(squares)

Output:

[1, 4, 9, 16, 25]

You can also include a condition:

even_numbers = [
    number for number in range(1, 11)
    if number % 2 == 0
]

Avoid overly complicated comprehensions when a normal loop would be easier to understand.

13. Modules and Packages

A module is a Python file containing code that can be imported into another program. A package organizes related modules.

Import a Built-in Module

import math

print(math.sqrt(25))
print(math.pi)

Import a Specific Function

from random import randint

print(randint(1, 10))

Install External Packages

Python commonly uses pip to install packages.

python -m pip install requests

The exact command may vary depending on the operating system and Python environment.

Virtual Environments

Virtual environments isolate project dependencies.

python -m venv .venv

Activate the environment using the appropriate command for your operating system, then install project dependencies within it.

14. Exception Handling

Exceptions are errors or unusual conditions that occur while a program runs.

Use try and except to handle expected failure conditions.

try:
    number = int(input("Enter a number: "))
    print(100 / number)
except ValueError:
    print("Please enter a valid integer.")
except ZeroDivisionError:
    print("The number cannot be zero.")

Else and Finally

try:
    number = int("25")
except ValueError:
    print("Conversion failed")
else:
    print(number)
finally:
    print("Operation completed")
  • except: Handles a matching exception.

  • else: Runs when the try block completes without an exception.

  • finally: Runs during normal exception handling regardless of whether an exception occurred.

Best practice: Catch specific exceptions where possible rather than using a broad except that can hide unexpected problems.

15. File Handling

Python can read and write files.

Read a Text File

with open("notes.txt", "r", encoding="utf-8") as file:
    content = file.read()

print(content)

Write to a File

with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("Learning Python")

The "w" mode overwrites an existing file.

Append to a File

with open("notes.txt", "a", encoding="utf-8") as file:
    file.write("\nPractice every day.")

The with statement manages the file's lifecycle and ensures it is closed appropriately.

Common file modes:

Mode

Purpose

"r"

Read

"w"

Write, replacing existing content

"a"

Append

"x"

Create a new file; fail if it exists

"b"

Binary mode modifier

16. Object-Oriented Programming Basics

Object-oriented programming organizes code using classes and objects.

Class: A definition describing attributes and behavior.

Object: An instance of a class.

Attribute: Data associated with an object.

Method: A function defined within a class.

Example:

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

    def introduce(self):
        return f"I am {self.name}, aged {self.age}."

student = Student("Alex", 21)
print(student.introduce())

Here, __init__() initializes an instance, and self refers to the current instance.

Other important OOP concepts include inheritance, encapsulation, and polymorphism.

17. Useful Built-in Functions

Function

Purpose

Example

print()

Display output

print("Hello")

input()

Read user input

input("Name: ")

len()

Return the number of items

len("Python")

type()

Return an object's type

type(10)

int()

Convert to integer where possible

int("10")

float()

Convert to floating-point number

float("3.5")

str()

Convert to string where supported

str(100)

sum()

Add numeric items

sum([1, 2, 3])

min()

Return the minimum item

min([3, 1, 2])

max()

Return the maximum item

max([3, 1, 2])

sorted()

Return a sorted list

sorted([3, 1, 2])

enumerate()

Iterate with an index and value

enumerate(["a", "b"])

zip()

Combine iterables element by element

zip([1, 2], ["a", "b"])

abs()

Return absolute value

abs(-5)

round()

Round a number

round(3.14159, 2)

18. Common Python Errors

Error

Meaning

Common solution

SyntaxError

Invalid Python syntax

Check brackets, quotes, and statements

IndentationError

Incorrect indentation

Align code blocks consistently

NameError

A name is not defined

Check spelling and scope

TypeError

An operation has an incompatible type

Check the types of values

ValueError

A value is inappropriate for an operation

Validate the input

IndexError

A sequence index is out of range

Check the collection length

KeyError

A dictionary key is missing

Check the key or use get()

ZeroDivisionError

Division by zero

Validate the divisor

FileNotFoundError

A requested file cannot be found

Check the path and file existence

ImportError

An import cannot be completed

Check package availability and import names

Debugging Checklist

  1. Read the complete error message.

  2. Identify the line where the failure occurred.

  3. Check variable names and data types.

  4. Inspect the relevant inputs.

  5. Reproduce the problem with a small example.

  6. Make one targeted correction.

  7. Test the corrected code.

19. Practical Python Example: Simple Expense Calculator

This example combines variables, input, numerical conversion, arithmetic, and formatted output.

item_name = input("Enter the expense name: ")
quantity = int(input("Enter quantity: "))
unit_price = float(input("Enter price per item: "))

total = quantity * unit_price

print(f"Expense: {item_name}")
print(f"Quantity: {quantity}")
print(f"Total cost: {total:.2f}")

Example input:

  • Expense name: Notebook

  • Quantity: 3

  • Price per item: 45

Output:

Expense: Notebook
Quantity: 3
Total cost: 135.00

This beginner example assumes valid input. A production-ready version should validate quantities, prices, and unexpected user entries.

20. Python Best Practices

  • Use meaningful variable and function names.

  • Follow consistent indentation.

  • Keep functions focused on a clear task.

  • Avoid repeating code unnecessarily.

  • Add comments when they explain something important.

  • Use exceptions to handle expected errors appropriately.

  • Validate user input.

  • Use virtual environments for project dependencies.

  • Write tests for important functionality.

  • Avoid storing passwords or API keys directly in source code.

  • Follow PEP 8 style guidance where practical.

  • Use version control for projects.

  • Consult official documentation when behavior is uncertain.

21. Python Beginner Revision Checklist

Fundamentals

  • Understand variables and assignment.

  • Recognize common data types.

  • Use arithmetic, comparison, and logical operators.

  • Work with strings and user input.

Control Flow

  • Write if, elif, and else statements.

  • Use for and while loops.

  • Understand break and continue.

Data Structures

  • Create and modify lists.

  • Understand tuples and sets.

  • Read and update dictionaries.

  • Use list comprehensions appropriately.

Functions and Modules

  • Define functions and return values.

  • Understand parameters and arguments.

  • Import modules.

  • Install and manage packages.

Practical Programming

  • Handle exceptions.

  • Read and write files.

  • Understand classes and objects.

  • Read error messages and debug code.

Conclusion

Python provides a practical foundation for programming, automation, data analytics, web development, and AI. By learning variables, data types, operators, conditions, loops, functions, collections, and error handling, beginners can build the skills needed for more advanced applications.

Use this cheat sheet as a quick reference while practicing Python. The most effective way to learn is to write small programs, test different inputs, read error messages carefully, and gradually build more complex projects.

#Python#Python Programming#Coding for Beginners#Programming Basics#Python Syntax

Related Posts