Arunav Goswami
Data Science Consultant at almaBetter
This Python cheat sheet covers basics to advanced concepts, regex, list slicing, loops and more. Perfect for quick reference and enhancing your coding skills.
Python is a versatile and powerful programming language used for various applications. Whether you’re preparing for an interview, working with data, or just getting started, this cheat sheet for Python will provide you with essential Python knowledge and tips.
int: Integer values
x = 10 |
float: Floating-point numbers
y = 3.14 |
str: Strings (text).
name = "Alice" |
bool: Boolean values
is_active = True |
list: Ordered, mutable collection of items.
fruits = ["apple", "banana", "cherry"] |
tuple: Ordered, immutable collection of items.
coordinates = (10.0, 20.0) |
dict: Collection of key-value pairs.
person = {"name": "Alice", "age": 30} |
set: Unordered collection of unique items.
unique_numbers = {1, 2, 3, 4} |
Comments:
# This is a comment |
Variables:
x = 5 name = "Alice" |
Printing:
print("Hello, World!") |
Indentation:
if x > 0: print("Positive") |
Arithmetic Operators
x + y # Addition x - y # Subtraction x * y # Multiplication x / y # Division x % y # Modulus x ** y # Exponentiation x // y # Floor division |
Comparison Operators
x == y # Equal to x != y # Not equal to x > y # Greater than x < y # Less than x >= y # Greater than or equal to x <= y # Less than or equal to |
Logical Operators
x and y # Logical AND x or y # Logical OR not x # Logical NOT |
Learn more: Operators in Python
if-elif-else:
if x > 0: print("Positive") elif x == 0: print("Zero") else: print("Negative") |
for Loop:
for i in range(5): print(i) |
while Loop:
count = 0 while count < 5: print(count) count += 1 |
Simple list comprehension
squares = [x**2 for x in range(10)] |
Conditional list comprehension
even_squares = [x**2 for x in range(10) if x % 2 == 0] |
Defining Functions:
def greet(name): return f"Hello, {name}!" |
Calling Functions:
print(greet("Alice")) |
Define a class
class MyClass: def __init__(self, name, age): self.name = name self.age = age def greet(self): return f"Hello, my name is {self.name} and I am {self.age} years old." |
Import a module
import math print(math.sqrt(16)) |
Import specific function from a module
from math import sqrt print(sqrt(16)) |
try, except, finally
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero") finally: print("This block always executes") |
Learn more: Exception Handling in Python
Open and read a file
with open('file.txt', 'r') as file: content = file.read() print(content) |
Write to a file
with open('file.txt', 'w') as file: file.write("Hello, World!") |
len(): Get the length of a list, tuple, dictionary, etc.
len(my_list) |
type(): Get the type of an object
type(my_dict) |
str(), int(), float(): Convert data types
str(123) # "123" int("123") # 123 float("3.14") # 3.14 |
list(): Convert to a list
list(my_tuple) |
NumPy: Numerical computing
import numpy as np arr = np.array([1, 2, 3]) |
Pandas: Data manipulation and analysis
import pandas as pd df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) |
Matplotlib: Plotting and visualization
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) plt.show() |
Match a Single Character:
pattern = r"a" |
Match a Digit:
pattern = r"\d" |
Match a Word:
pattern = r"\w+" |
Match Whitespace:
pattern = r"\s" |
Importing the re Module:
import re |
Search for a Pattern:
result = re.search(r"\d+", "The price is 100 dollars") |
Find All Matches:
results = re.findall(r"\d+", "The prices are 100, 200, and 300 dollars") |
Replace a Pattern:
updated_text = re.sub(r"\d+", "number", "The price is 100 dollars") |
Learn more: Regex in Python
Importing Pandas:
import pandas as pd |
Creating a DataFrame:
data = {"name": ["Alice", "Bob"], "age": [25, 30]} df = pd.DataFrame(data) |
Reading Data from a CSV File:
df = pd.read_csv("data.csv") |
Writing Data to a CSV File:
df.to_csv("output.csv", index=False) |
Viewing Data:
df.head() df.info() df.describe() |
Selecting Data:
df["name"] df[["name", "age"]] df.loc[0] df.iloc[0] |
Filtering Data:
df[df["age"] > 25] |
Grouping Data:
df.groupby("age").mean() |
By mastering these Python concepts, you’ll be well-prepared for Python interviews and equipped to handle various programming tasks. This cheat sheet is designed to be a quick reference guide for both beginners and experienced Python programmers.