Python Cheat Sheet

A comprehensive guide to Python syntax and common operations.


1. Basic Syntax

# Print to console
print("Hello, World!")

# Variables
x = 10
y = 20.5
name = "Python"

# Data Types
integer = 42
floating_point = 3.14
string = "Hello"
boolean = True
none_type = None
            

2. Data Structures

Lists

# List creation and operations
my_list = [1, 2, 3, 4, 5]
my_list.append(6)  # Add an item
my_list.pop()      # Remove last item
my_list[1:3]       # Slicing
            

Dictionaries

# Dictionary creation
my_dict = {"name": "Alice", "age": 25}
my_dict["city"] = "New York"  # Add key-value pair
value = my_dict.get("name")   # Get value
            

3. Control Flow

# If-else
if x > 0:
    print("Positive")
else:
    print("Non-positive")

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

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

4. Functions

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

# Call a function
message = greet("Python")
print(message)
            

5. Classes and Objects

# Define a class
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        return "Woof!"

# Create an object
my_dog = Dog("Buddy", 3)
print(my_dog.bark())
            

6. File Handling

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

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

7. Exception Handling

# Try-except block
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("Execution completed.")
            

8. Useful Modules

import math
print(math.sqrt(16))  # Square root

import random
print(random.randint(1, 10))  # Random number between 1 and 10

import datetime
print(datetime.datetime.now())  # Current date and time