Python Cheat Sheet
1. Basics
• Print:
python
Copy
print("Hello, World!")
• Variables:
python
Copy
x = 10
name = "Alice"
• Comments:
python
Copy
# This is a single-line comment
"""
This is a
multi-line comment
"""
2. Data Types
• Numbers:
python
Copy
x = 10 # Integer
y = 3.14 # Float
z = 2 + 3j # Complex
• Strings:
python
Copy
s = "Python"
print(s[0]) # P
print(len(s)) # 6
• Lists:
python
Copy
my_list = [1, 2, 3]
my_list.append(4) # [1, 2, 3, 4]
my_list[0] = 10 # [10, 2, 3, 4]
• Tuples:
python
Copy
my_tuple = (1, 2, 3)
• Dictionaries:
python
Copy
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"]) # Alice
• Sets:
python
Copy
my_set = {1, 2, 3}
my_set.add(4) # {1, 2, 3, 4}
3. Control Flow
• If-Else:
python
Copy
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is 10")
else:
print("x is less than 10")
• For Loop:
python
Copy
for i in range(5):
print(i) # 0, 1, 2, 3, 4
• While Loop:
python
Copy
while x > 0:
print(x)
x -= 1
4. Functions
• Define Function:
python
Copy
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
• Lambda Function:
python
Copy
square = lambda x: x ** 2
print(square(5)) # 25
5. File Handling
• Read File:
python
Copy
with open("file.txt", "r") as file:
content = file.read()
• Write File:
python
Copy
with open("file.txt", "w") as file:
file.write("Hello, World!")
6. Error Handling
• Try-Except:
python
Copy
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
7. Classes and Objects
• Define Class:
python
Copy
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name}"
• Create Object:
python
Copy
person = Person("Alice", 25)
print(person.greet()) # Hello, my name is Alice
8. Libraries
• Import Library:
python
Copy
import math
print(math.sqrt(16)) # 4.0
• Install Library:
bash
Copy
pip install numpy
9. List Comprehensions
• Create List:
python
Copy
squares = [x ** 2 for x in range(10)]
10. Useful Functions
• Range:
python
Copy
numbers = list(range(1, 6)) # [1, 2, 3, 4, 5]
• Map:
python
Copy
numbers = [1, 2, 3]
squared = list(map(lambda x: x ** 2, numbers)) # [1, 4, 9]
• Filter:
python
Copy
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2]