Bytes
PythonData Science

Python Cheat Sheet (Basics to Advanced Python Cheat Sheet)

Last Updated: 30th July, 2024
icon

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.

1. Python Data Types Cheat Sheet

Basic Data Types:

int: Integer values

x = 10

float: Floating-point numbers

y = 3.14

str: Strings (text).

name = "Alice"

bool: Boolean values

is_active = True

Compound Data Types:

list: Ordered, mutable collection of items.

fruits = ["apple""banana""cherry"]

tuple: Ordered, immutable collection of items.

coordinates = (10.020.0)

dict: Collection of key-value pairs.

person = {"name""Alice""age"30}

set: Unordered collection of unique items.

unique_numbers = {1234}

2. Python Syntax Cheat Sheet

Basic Syntax:

Comments:

# This is a comment

Variables:

x = 5
name = "Alice"

Printing:

print("Hello, World!")

Indentation:

if x > 0:
    print("Positive")

Operators

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

and# Logical AND
or y   # Logical OR
not x    # Logical NOT

Learn more: Operators in Python

Control Flow:

if-elif-else:

if x > 0:
    print("Positive")
elif x == 0:
    print("Zero")
else:
    print("Negative")

for Loop:

forin range(5):
    print(i)

while Loop:

count = 0
while count < 5:
    print(count)
    count += 1

List Comprehensions

Simple list comprehension

squares = [x**2 forin range(10)]

Conditional list comprehension

even_squares = [x**2 forin range(10if x % 2 == 0]

Functions:

Defining Functions:

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

Calling Functions:

print(greet("Alice"))

Classes

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."

Importing Modules

Import a module

import math
print(math.sqrt(16))

Import specific function from a module

from math import sqrt
print(sqrt(16))

Exception Handling

try, except, finally

try:
    result = 100
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("This block always executes")

Learn more: Exception Handling in Python

3. Python File HandlingCheat Sheet

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!")

4. Python Commonly Used Functions

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)

5. Useful Libraries

NumPy: Numerical computing

import numpy as np
arr = np.array([123])

Pandas: Data manipulation and analysis

import pandas as pd
df = pd.DataFrame({"A": [123], "B": [456]})

Matplotlib: Plotting and visualization

import matplotlib.pyplot as plt
plt.plot([123], [456])
plt.show()

6. Python Regex Cheat Sheet

Common Regex Patterns:

Match a Single Character:

pattern = r"a"

Match a Digit:

pattern = r"\d"

Match a Word:

pattern = r"\w+"

Match Whitespace:

pattern = r"\s"

Using Regex in Python:

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

7. Python Pandas Cheat Sheet

Working with Pandas:

Importing Pandas:

import pandas as pd

Creating a DataFrame:

data = {"name": ["Alice""Bob"], "age": [2530]}
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)

Common DataFrame Operations:

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()

8. Python Cheat Sheet for Interview Preparation

Key Topics to Review:

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.

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter