Python Cheat Sheet
Python Cheat Sheet
1. Basics
# Comments
# This is a single-line comment
'''This is a multi-line comment'''
2. Operators
# Arithmetic
a, b = 10, 3
print(a + b) # 13 (Addition)
print(a - b) # 7 (Subtraction)
print(a * b) # 30 (Multiplication)
print(a / b) # 3.33 (Division)
print(a // b) # 3 (Floor Division)
print(a % b) # 1 (Modulus)
print(a ** b) # 1000 (Exponentiation)
3. Control Flow
# If-Else
x = 20
if x > 10:
print("Greater than 10")
elif x == 10:
print("Equal to 10")
else:
print("Less than 10")
# Loops
for i in range(5): # 0 to 4
print(i)
4. Functions
# Function Definition
def greet(name):
return f"Hello, {name}!"
# Lambda Function
square = lambda x: x ** 2
print(square(5)) # 25
5. Data Structures
# List
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # 1
my_list.append(6) # Add element
my_list.pop() # Remove last element
# Tuple (Immutable)
my_tuple = (1, 2, 3)
6. File Handling
# Writing to a file
with open("test.txt", "w") as file:
file.write("Hello, world!")
# Reading a file
with open("test.txt", "r") as file:
content = file.read()
print(content)
7. Exception Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Execution completed.")
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hi, I'm {self.name}!"
p1 = Person("Nitin", 15)
print(p1.greet()) # Hi, I'm Nitin!
import math
print(math.sqrt(25)) # 5.0
import random
print(random.randint(1, 10)) # Random number between 1 and 10
import datetime
print(datetime.datetime.now()) # Current date & time
# List Slicing
my_list = [10, 20, 30, 40, 50]
print(my_list[1:4]) # [20, 30, 40]
# Generators
def gen():
yield 1
yield 2
yield 3
g = gen()
print(next(g)) # 1
print(next(g)) # 2
# Decorators
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()