Python Code Formulas with Examples
1. Math and Arithmetic
- Addition: Adds two numbers.
result = 5 + 3
- Subtraction: Subtracts second number from the first.
result = 10 - 7
- Square Root: Finds the square root of a number.
import math
result = math.sqrt(16)
2. String Operations
- Concatenation: Combines two strings.
result = "Hello" + " " + "World!"
- Substring Check: Checks if a substring exists.
if "World" in "Hello World": print("Found!")
3. List Operations
- Sum of Elements: Calculates the sum of all list elements.
result = sum([1, 2, 3, 4])
- Sort List: Sorts a list in ascending order.
sorted_list = sorted([4, 2, 3, 1])
4. Conditional Statements
Python Code Formulas with Examples
- Check Even/Odd: Determines if a number is even or odd.
if num % 2 == 0:
print('Even')
else:
print('Odd')
5. Loops
- For Loop: Prints numbers from 1 to 5.
for i in range(1, 6):
print(i)
- While Loop: Prints a countdown.
count = 3
while count > 0:
print(count)
count -= 1