Python Code Formulas: A Quick Reference Guide
1. Math and Arithmetic
- Addition: result = a + b
- Subtraction: result = a - b
- Multiplication: result = a * b
- Division: result = a / b
- Floor Division: result = a // b
- Modulo (Remainder): result = a % b
- Power: result = a ** b or math.pow(a, b)
- Square Root: import math; result = math.sqrt(a)
2. String Operations
- Concatenation: result = str1 + str2
- Repetition: result = str1 * 3
- Length: length = len(str1)
- Substring Check: if "sub" in str1: print("Found!")
- Replace: new_str = str1.replace("old", "new")
3. List Operations
- Sum of Elements: result = sum(lst)
- Maximum Element: max_val = max(lst)
- Minimum Element: min_val = min(lst)
- Sort List: sorted_list = sorted(lst)
- Reverse List: lst.reverse()
4. Conditional Statements
- Check Even/Odd:
if num % 2 == 0:
print("Even")
else:
print("Odd")
5. Loops
- For Loop:
for i in range(1, 11):
print(i)
- While Loop:
while num > 0:
print(num)
num -= 1
6. File Operations
- Read a File:
with open("file.txt", "r") as file:
content = file.read()
- Write to a File:
with open("file.txt", "w") as file:
file.write("Hello, World!")
7. Importing Modules
- Random Number:
import random
result = random.randint(1, 100)
- Current Date:
from datetime import datetime
now = datetime.now()
8. Algorithms
- Factorial:
import math
result = math.factorial(n)
- Fibonacci Series:
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
9. Error Handling
- Try-Except Block:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
10. Python Shortcuts
- One-Liner if-else:
result = "Even" if num % 2 == 0 else "Odd"
- List Comprehension:
squares = [x**2 for x in range(10)]