Python Cheatsheat
Python Cheatsheat
1. Basic Syntax
Print Statement:
print("Hello, World!")
Comments:
# This is a single-line comment
"""This is a
multi-line comment"""
Variables:
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
2. Data Types
Examples:
is_happy = True # Boolean
numbers = [1, 2, 3] # List
point = (4, 5) # Tuple
info = {"name": "Bob", "age": 25} # Dictionary
unique_numbers = {1, 2, 3} # Set
3. Control Flow
If Statements:
age = 18
if age >= 18:
print("Adult")
else:
print("Minor")
Loops:
# For Loop
for i in range(5):
print(i)
# While Loop
count = 0
while count < 5:
print(count)
count += 1
4. Functions
5. Lists
List Operations:
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Add an item
fruits.remove("banana") # Remove an item
print(fruits[0]) # Access by index
6. Dictionaries
Dictionary Operations:
person = {"name": "John", "age": 30}
print(person["name"]) # Access value
person["age"] = 31 # Update value
person["city"] = "NY" # Add key-value pair
7. File Handling
8. Error Handling
Try-Except Blocks:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Common Functions:
len(sequence) # Get length
type(variable) # Get type
str(), int(), float() # Convert types
sorted(list) # Sort list
10. Modules
Importing Modules:
import math
print(math.sqrt(16))
from random import randint
print(randint(1, 10))