Python_Programming_Cheat_Sheet
Python_Programming_Cheat_Sheet
1. Basics
# Print output
print("Hello, World!")
# Variables
x = 5
name = "Alice"
# Data Types
int, float, str, bool, list, tuple, dict, set
2. Control Flow
# Conditional statements
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
# Loops
for i in range(5):
print(i)
while x > 0:
x -= 1
3. Functions
def greet(name):
return "Hello " + name
print(greet("Bob"))
4. Data Structures
# List
fruits = ["apple", "banana", "cherry"]
fruits.append("mango")
# Dictionary
person = {"name": "John", "age": 30}
print(person["name"])
# Tuple
point = (10, 20)
# Set
nums = {1, 2, 3}
nums.add(4)
5. List Comprehension
squares = [x**2 for x in range(5)]
6. Object-Oriented Programming
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name + " says woof!")
dog1 = Dog("Buddy")
dog1.bark()
7. File Handling
# Write to a file
with open("file.txt", "w") as f:
f.write("Hello!")
9. Exception Handling
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Done")