Python Cheatsheet
1. Variables and Data Types
- Strings: text = "Hello World"
- Integers: num = 42
- Floats: pi = 3.14
- Booleans: is_valid = True
- Lists: fruits = ["apple", "banana"]
- Tuples: point = (1, 2)
- Dictionaries: data = {"name": "Alice", "age": 25}
2. Conditional Statements
if condition:
# Code
elif other_condition:
# Code
else:
# Code
3. Loops
# For Loop
for item in list:
# Code
# While Loop
while condition:
# Code
4. Functions
def function_name(parameters):
# Code
return result
# Example
def add(a, b):
return a + b
5. Classes and Objects
class ClassName:
def __init__(self, param1, param2):
self.param1 = param1
self.param2 = param2
def method(self):
# Code
# Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name}"
6. File Handling
# Read File
with open("file.txt", "r") as file:
content = file.read()
# Write File
with open("file.txt", "w") as file:
file.write("Hello World")
7. Common Built-in Functions
- len(obj): Length of an object
- type(obj): Type of an object
- print(*args): Print to console
- range(start, stop, step): Generate sequence
8. List Comprehensions
squares = [x**2 for x in range(10) if x % 2 == 0]
9. Exception Handling
try:
# Code that might raise an exception
except Exception as e:
# Handle exception
finally:
# Always executed
10. Libraries and Imports
import module_name
# Example
import math
print(math.sqrt(16))