Programming·

Python Cheat Sheet

This Python cheat sheet covers most of the commonly used Python syntax and features

Basic Syntax

# Print
print("Hello, World!")

# Variable Assignment
x = 5
y = "Python"

# Comments
# This is a single-line comment
"""
This is a multi-line comment
"""

# Data Types
integer = 10
float_number = 10.5
string = "Hello"
boolean = True
none_value = None

Data Structures

# List
my_list = [1, 2, 3, "four", 5.0]

# Tuple
my_tuple = (1, 2, 3, "four", 5.0)

# Dictionary
my_dict = {"name": "Alice", "age": 25}

# Set
my_set = {1, 2, 3, 4, 5}

Control Structures

# Conditional Statements
if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")

# Loops
# for loop
for i in range(5):
    print(i)

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

Functions

# Defining a Function
def greet(name):
    return f"Hello, {name}!"

# Calling a Function
print(greet("Alice"))

Classes and Objects

# Defining a Class
class Person:
    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."

# Creating an Object
person = Person("Alice", 25)
print(person.greet())

File Operations

# Reading a File
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

# Writing to a File
with open("example.txt", "w") as file:
    file.write("Hello, World!")

Exception Handling

try:
    # Code that might raise an exception
    result = 10 / 0
except ZeroDivisionError:
    print("Division by zero error")
finally:
    print("This will execute no matter what")

Common Libraries

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

# Pandas
import pandas as pd
df = pd.DataFrame({"Name": ["Alice", "Bob"], "Age": [25, 30]})

# Matplotlib
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()

# Requests
import requests
response = requests.get("https://api.github.com")
print(response.json())

Advanced Topics

# List Comprehension
squares = [x**2 for x in range(10)]

# Lambda Functions
add = lambda a, b: a + b
print(add(5, 3))

# Decorators
def decorator_function(original_function):
    def wrapper_function():
        print("Wrapper executed before {}".format(original_function.__name__))
        return original_function()
    return wrapper_function

@decorator_function
def display():
    print("Display function ran")

display()