Python is one of the most popular programming languages in the world, and for good reason. Its elegant syntax, powerful libraries, and wide range of applications make it a top choice for both beginners and seasoned developers alike. Whether you’re developing web applications, crunching data for insights, automating tasks, or even dabbling in artificial intelligence, Python has got you covered. But with such a vast range of capabilities, getting a handle on all of Python’s features can be a bit daunting. That’s where this guide comes in. We’ve put together a comprehensive Python cheat sheet that will serve as your quick reference guide as you embark on your Python programming journey.

 Python Basics

python
print("Hello, World!")

Comments

python
# This is a single-line comment

Variables and Data Types

Variables

python
x = 5
y = "Hello, World!"

Data Types

python
int: 5
float: 5.0
str: "Hello, World!"
list: [1, 2, 3]
tuple: (1, 2, 3)
dict: {"key": "value"}
bool: True, False

Type Conversion

python
int(5.5) # 5
str(5)   # "5"

Operators

Arithmetic Operators

python
`+, -, *, /, %, **, //`

Assignment Operators

python
`=, +=, -=, *=, /=, %=, **=, //=`

Comparison Operators

python
`==, !=, >, <, >=, <=`

Logical Operators

python
`and, or, not`

Control Flow

If Statements

python
if x > y:
print("x is greater than y")
elif x == y:
print("x is equal to y")
else:
print("x is less than y")

While Loops

python
while x > 0:
print(x)
x -= 1

For Loops

python
for x in range(0, 5):
print(x)
for item in list:
print(item)

List Comprehensions

python
[x**2 for x in range(0, 5)]

Functions

Function Definition

python
def my_function():
print("Hello, World!")

Calling a Function

python
my_function()

Parameters and Arguments

python
def my_function(x, y):
print(x + y)
my_function(3, 5) # prints 8

Default Parameter Value

python
def my_function(x=1):
print(x)
my_function() # prints 1
my_function(5) # prints 5

Return Values

python
def square(x):
return x**2

Classes and Objects

Defining a Class

python
class MyClass:
x = 5

Creating an Object

python
p1 = MyClass()
print(p1.x)

The init() Function

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

Object Methods

python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)

Modules

Importing a Module

python
import math

Using a Function from a Module

python
import math
x = math.sqrt(64)

Importing Only Part of a Module

python
from math import sqrt

File Handling

Writing to a file

python
f = open("myfile.txt", "w")
f.write("Hello, World!")
f.close()

Reading From a File

python
f = open("myfile.txt", "r")
print(f.read())
f.close()

Appending to a File

python
f = open("myfile.txt", "a")
f.write("\nHello, again!")
f.close()

Other Useful Features

List Methods

python
my_list.append("item") # Adds an item to the end of the list
my_list.remove("item") # Removes an item from the list
my_list.pop() # Removes the last item from the list
my_list.index("item") # Returns the index of an item in the list
my_list.count("item") # Counts the number of times an item appears in the list

Dictionary Methods

python
my_dict.get("key") # Returns the value for a key
my_dict.keys() # Returns a new view of the dictionary's keys
my_dict.values() # Returns a new view of the dictionary's values
my_dict.update({"key": "value"}) # Updates the dictionary with the specified key-value pairs
my_dict.pop("key") # Removes the item with the specified key

String Methods

python
my_str.upper() # Returns the string in upper case
my_str.lower() # Returns the string in lower case
my_str.replace("old", "new") # Replaces a substring with another substring
my_str.split(",") # Splits the string at the specified separator, and returns a list

Lambda Function

python
x = lambda a : a + 10
print(x(5)) # prints 15

Error Handling

python
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

NumPy (Numerical Python)

python
import numpy as np
a = np.array([1, 2, 3]) # Creates a numpy array

Pandas

python
import pandas as pd
df = pd.read_csv('file.csv') # Reads a CSV file and creates a DataFrame

Matplotlib

python
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4]) # Plots a simple line graph
plt.ylabel('some numbers') # Adds a label to the y-axis
plt.show() # Displays the graph