Control Flow in Python
Control flow is the order in which individual statements, instructions, or function calls are executed. Python provides several structures for controlling program flow:
1. If Statements (Selection)
If statements allow you to execute different code based on conditions:
# Basic if statement x = 10 if x > 5: print("x is greater than 5") # if-else statement age = 18 if age >= 18: print("You are an adult") else: print("You are a minor") # if-elif-else statement score = 85 if score >= 90: print("A grade") elif score >= 80: print("B grade") elif score >= 70: print("C grade") elif score >= 60: print("D grade") else: print("Failed")
2. For Loops
For loops are used to iterate over sequences:
# Looping through a range for i in range(5): print(i) # Prints 0, 1, 2, 3, 4 # Looping through a list fruits = ["apple", "banana", "orange"] for fruit in fruits: print(fruit) # Enumerate for index and value for index, fruit in enumerate(fruits): print(f"{index}: {fruit}") # Nested loops for i in range(3): for j in range(2): print(f"i={i}, j={j}")
3. While Loops
While loops repeat as long as a condition is true:
# Basic while loop count = 0 while count < 5: print(count) count += 1 # Break statement while True: user_input = input("Enter 'quit' to exit: ") if user_input == "quit": break # Continue statement for i in range(5): if i == 2: continue # Skip 2 print(i)
4. Loop Control Statements
Python provides several ways to control loop execution:
# Break - exit the loop for i in range(10): if i == 5: break print(i) # Continue - skip to next iteration for i in range(5): if i == 2: continue print(i) # Pass - do nothing for i in range(5): if i == 2: pass # Placeholder else: print(i)
5. List Comprehensions
A concise way to create lists using loops:
# Traditional loop squares = [] for x in range(5): squares.append(x**2) # List comprehension squares = [x**2 for x in range(5)] # With condition even_squares = [x**2 for x in range(10) if x % 2 == 0]
6. Combining Loops and Conditions
You can combine loops and conditions for more complex control flow:
# Find prime numbers def is_prime(n): if n < 2: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True # Print prime numbers up to 20 for num in range(20): if is_prime(num): print(f"{num} is prime")
Conclusion
Control flow in Python allows for the execution of statements, instructions, or function calls in a specific order. This can be achieved through various structures:
- If Statements for making decisions based on conditions.
- For Loops for iterating over sequences such as ranges or lists.
- While Loops for repeating actions while a condition is true.
- Loop Control Statements like break, continue, and pass for controlling loop execution.
- List Comprehensions for creating lists in a concise way.
- Combining Loops and Conditions for more complex control flow, such as identifying prime numbers in a given range.