18
JulPython Cheat Sheet: Full Guide
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.
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 Type | Description | Example |
---|---|---|
int | Whole numbers | x = 10 |
float | Decimal numbers | pi = 3.14 |
str | Text strings | name = "Bob" |
bool | Boolean (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:
Function | Purpose | Example |
---|---|---|
int() | Convert to integer | int("5") → 5 |
float() | Convert to float | float("3.2") → 3.2 |
str() | Convert to string | str(10) → "10" |
bool() | Convert to boolean | bool(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 Type | Description |
---|---|
Arithmetic Operators | Perform basic mathematical operations |
Comparison Operators | Compare two values |
Assignment Operators | Assign values to variables |
Logical Operators | Combine multiple conditions |
Identity Operators | Compare memory location |
Membership Operators | Check for membership in sequences |
Bitwise Operators | Perform bit-level operations |
1. Arithmetic Operators
Used to perform mathematical operations.
Operator | Description | Example (a = 10, b = 3) | Result |
---|---|---|---|
+ | Addition | a + b | 13 |
- | Subtraction | a - b | 7 |
* | Multiplication | a * b | 30 |
/ | Division | a / b | 3.33 |
// | Floor Division | a // b | 3 |
% | Modulus | a % b | 1 |
** | Exponentiation | a ** b | 1000 |
2. Comparison Operators
Used to compare values and return Boolean results.
Operator | Description | Example | Result |
---|---|---|---|
== | Equal to | a == b | False |
!= | Not equal to | a != b | True |
> | Greater than | a > b | True |
< | Less than | a < b | False |
>= | Greater than or equal | a >= b | True |
<= | Less than or equal | a <= b | False |
3. Assignment Operators
Used to assign values and perform shorthand operations.
Operator | Description | Example | Equivalent |
---|---|---|---|
= | Assign | x = 5 | - |
+= | Add and assign | x += 3 | x = x + 3 |
-= | Subtract and assign | x -= 3 | x = x - 3 |
*= | Multiply and assign | x *= 3 | x = x * 3 |
/= | Divide and assign | x /= 3 | x = x / 3 |
//= | Floor divide and assign | x //= 3 | x = x // 3 |
%= | Modulus and assign | x %= 3 | x = x % 3 |
**= | Power and assign | x **= 3 | x = x ** 3 |
4. Logical Operators
Used to combine conditional statements.
Operator | Description | Example | Result |
---|---|---|---|
and | True if both are true | True and False | False |
or | True if at least one is true | True or False | True |
not | Inverts the result | not True | False |
5. Identity Operators
Used to compare memory locations (not just values).
Operator | Description | Example | Result |
---|---|---|---|
is | True if same object | a is b | False |
is not | True if different objects | a 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.
Operator | Description | Example | Result |
---|---|---|---|
in | True if present | "a" in "apple" | True |
not in | True if not present | "z" not in "apple" | True |
7. Bitwise Operators
Used for binary-level operations.
Operator | Description | Example | Result |
---|---|---|---|
& | AND | 5 & 3 | 1 |
| | OR | 5 | 3 | 7 |
^ | XOR | 5 ^ 3 | 6 |
~ | NOT | ~5 | -6 |
<< | Left Shift | 5 << 1 | 10 |
>> | Right Shift | 5 >> 1 | 2 |
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 Structure | Ordered | Mutable | Allows Duplicates | Indexed |
---|---|---|---|---|
List | Yes | Yes | Yes | Yes |
Tuple | Yes | No | Yes | Yes |
Set | No | Yes | No | No |
Dictionary | No (3.7+ maintains insertion order) | Yes | Keys - No, Values - Yes | Keys 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
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
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
Purpose | Library |
---|---|
Data Analysis | pandas, numpy |
Web Development | Flask, Django |
Machine Learning | scikit-learn, TensorFlow |
Web Scraping | BeautifulSoup, requests |
Automation | selenium, pyautogui |
Visualization | matplotlib, 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
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.