Python Cheat Sheet
Python Cheat Sheet
1. Basics
• Print:
python
Copy
print("Hello, World!")
• Variables:
python
Copy
x = 10
name = "Alice"
• Comments:
python
Copy
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
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
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")
• 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
8. Libraries
• Import Library:
python
Copy
import math
print(math.sqrt(16)) # 4.0
• Install Library:
bash
Copy
9. List Comprehensions
• Create List:
python
Copy
• Range:
python
Copy
Copy
numbers = [1, 2, 3]
squared = list(map(lambda x: x ** 2, numbers)) # [1, 4, 9]
• Filter:
python
Copy