Python Cheat Sheet for Beginners
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 Python3. Variables in Python
A variable is a name that refers to a value.
name = "Alex"
age = 25
height = 5.8
is_student = TrueIn this example:
namerefers to a string.agerefers to an integer.heightrefers to a floating-point number.is_studentrefers 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 = 5Invalid 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 |
|---|---|---|
| Whole numbers |
|
| Decimal numbers |
|
| Text |
|
| True or false values |
|
| Ordered, mutable collection |
|
| Ordered, immutable collection |
|
| Collection of unique elements |
|
| Key-value mapping |
|
| Represents the absence of a value |
|
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]) # nString Slicing
language = "Python"
print(language[0:3]) # Pyt
print(language[2:]) # thon
print(language[:4]) # PythThe 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 |
|
| Subtraction |
|
| Multiplication |
|
| Division |
|
| Floor division |
|
| Modulus (remainder) |
|
| Exponentiation |
|
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) # FalseComparison 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, 8The 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 += 1Make 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 requestsThe exact command may vary depending on the operating system and Python environment.
Virtual Environments
Virtual environments isolate project dependencies.
python -m venv .venvActivate 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 thetryblock 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 |
|---|---|
| Read |
| Write, replacing existing content |
| Append |
| Create a new file; fail if it exists |
| 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 |
|---|---|---|
| Display output |
|
| Read user input |
|
| Return the number of items |
|
| Return an object's type |
|
| Convert to integer where possible |
|
| Convert to floating-point number |
|
| Convert to string where supported |
|
| Add numeric items |
|
| Return the minimum item |
|
| Return the maximum item |
|
| Return a sorted list |
|
| Iterate with an index and value |
|
| Combine iterables element by element |
|
| Return absolute value |
|
| Round a number |
|
18. Common Python Errors
Error | Meaning | Common solution |
|---|---|---|
| Invalid Python syntax | Check brackets, quotes, and statements |
| Incorrect indentation | Align code blocks consistently |
| A name is not defined | Check spelling and scope |
| An operation has an incompatible type | Check the types of values |
| A value is inappropriate for an operation | Validate the input |
| A sequence index is out of range | Check the collection length |
| A dictionary key is missing | Check the key or use |
| Division by zero | Validate the divisor |
| A requested file cannot be found | Check the path and file existence |
| An import cannot be completed | Check package availability and import names |
Debugging Checklist
Read the complete error message.
Identify the line where the failure occurred.
Check variable names and data types.
Inspect the relevant inputs.
Reproduce the problem with a small example.
Make one targeted correction.
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.00This 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, andelsestatements.Use
forandwhileloops.Understand
breakandcontinue.
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.



