Python Loops and Conditionals
Control flow is essential in programming. Python provides powerful tools for making decisions and repeating actions. This tutorial covers conditional statements (if/elif/else) and loops (for/while), which let your programs make choices and handle repetitive tasks efficiently.
Conditional Statements
Conditional statements allow your program to make decisions based on conditions. The most common is the if statement.
Basic if Statement
age = 18
if age >= 18:
print("You are an adult")
print("You can vote")
print("This always runs") # Not indented, runs regardlessif-else Statement
temperature = 25
if temperature > 30:
print("It's hot outside")
else:
print("It's not too hot")
# With user input
name = input("Enter your name: ")
if name:
print(f"Hello, {name}!")
else:
print("You didn't enter a name")if-elif-else Statement
Use elif (else if) for multiple conditions.
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Your grade is: {grade}")Nested Conditionals
You can nest if statements inside each other.
age = 25
has_license = True
if age >= 18:
if has_license:
print("You can drive")
else:
print("You need a license to drive")
else:
print("You're too young to drive")Logical Operators
Combine conditions with and, or, and not.
age = 20
is_student = True
# and: both conditions must be true
if age >= 18 and is_student:
print("You're an adult student")
# or: at least one condition must be true
if age < 18 or age > 65:
print("You might qualify for a discount")
# not: reverses the condition
if not is_student:
print("You're not a student")Ternary Operator
A compact way to write simple if-else statements.
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # "adult"
# Multiple conditions
temperature = 25
weather = "hot" if temperature > 30 else "cold" if temperature < 10 else "moderate"
print(weather) # "moderate"Loops
Loops allow you to repeat code multiple times. Python has two main types: for and while loops.
For Loops
For loops iterate over sequences like lists, strings, or ranges.
# Loop through a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(f"I like {fruit}")
# Loop through a string
for letter in "Python":
print(letter)
# Loop through a range
for number in range(5): # 0 to 4
print(number)
for number in range(1, 6): # 1 to 5
print(number)
for number in range(0, 10, 2): # Even numbers: 0, 2, 4, 6, 8
print(number)While Loops
While loops continue as long as a condition is true.
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1
# Infinite loop with break
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == 'quit':
break
print(f"You entered: {user_input}")Loop Control Statements
break: Exit the loop immediatelycontinue: Skip the rest of the current iteration and move to the next
# break example
for number in range(10):
if number == 5:
break
print(number) # Prints 0, 1, 2, 3, 4
# continue example
for number in range(5):
if number == 2:
continue
print(number) # Prints 0, 1, 3, 4 (skips 2)Nested Loops
Loops inside loops.
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
print() # Empty line between rowsList Comprehensions
A compact way to create lists using loops.
# Traditional way
squares = []
for x in range(5):
squares.append(x**2)
# List comprehension
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
# Nested list comprehensions
matrix = [[i*j for j in range(3)] for i in range(3)]
print(matrix) # [[0, 0, 0], [0, 1, 2], [0, 2, 4]]Practical Examples
Finding Maximum Value
numbers = [3, 7, 2, 9, 5, 1]
maximum = numbers[0]
for number in numbers:
if number > maximum:
maximum = number
print(f"The maximum value is: {maximum}")Simple Calculator
while True:
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Quit")
choice = input("Choose an operation (1-5): ")
if choice == '5':
break
if choice in ['1', '2', '3', '4']:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
result = num1 + num2
print(f"{num1} + {num2} = {result}")
elif choice == '2':
result = num1 - num2
print(f"{num1} - {num2} = {result}")
elif choice == '3':
result = num1 * num2
print(f"{num1} * {num2} = {result}")
elif choice == '4':
if num2 != 0:
result = num1 / num2
print(f"{num1} / {num2} = {result}")
else:
print("Cannot divide by zero")
else:
print("Invalid choice. Please try again.")
print()Password Validation
def validate_password(password):
has_upper = False
has_lower = False
has_digit = False
for char in password:
if char.isupper():
has_upper = True
elif char.islower():
has_lower = True
elif char.isdigit():
has_digit = True
return len(password) >= 8 and has_upper and has_lower and has_digit
password = input("Enter a password: ")
if validate_password(password):
print("Password is valid")
else:
print("Password must be at least 8 characters with upper, lower, and digits")Common Patterns
Iterating with Index
fruits = ["apple", "banana", "orange"]
# Using enumerate
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Manual index tracking
for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")Looping Over Dictionaries
person = {"name": "Alice", "age": 30, "city": "New York"}
for key in person:
print(f"{key}: {person[key]}")
for key, value in person.items():
print(f"{key}: {value}")Finding Items in Lists
numbers = [1, 3, 5, 7, 9]
target = 5
found = False
for number in numbers:
if number == target:
found = True
break
if found:
print(f"{target} was found in the list")
else:
print(f"{target} was not found in the list")Best Practices
- Use for loops when you know the number of iterations
- Use while loops for indefinite repetition
- Avoid infinite loops by ensuring exit conditions
- Use meaningful variable names in loops
- Consider list comprehensions for simple transformations
- Use enumerate() when you need both index and value
- Break complex nested loops into functions
Performance Considerations
- For loops are generally faster than while loops for iterating over known sequences
- List comprehensions are more efficient than traditional loops for creating lists
- Use break and continue sparingly to keep code readable
- Avoid modifying lists while iterating over them
Summary
Control flow statements are fundamental to programming:
| Statement | Purpose | Example |
|---|---|---|
if | Execute code if condition is true | if x > 0: |
elif | Check alternative condition | elif x < 0: |
else | Execute if no conditions match | else: |
for | Iterate over sequence | for item in items: |
while | Repeat while condition is true | while x < 10: |
break | Exit loop immediately | break |
continue | Skip to next iteration | continue |
Mastering these concepts will allow you to write more complex and useful Python programs.
External Resources:
Related Tutorials: