Python Loops
Loops allow you to repeat blocks of code multiple times. There are two main types of loops in Python: while loops and for loops. Each loop type is designed for different kinds of repetitive tasks.
Table of Contents
While Loops
A while loop repeatedly executes a block of code as long as a condition is True. The loop continues until the condition becomes False.
Basic Syntax:
while condition:
# Code to run while the condition is True
condition: This is an expression that evaluates toTrueorFalse. If it’sTrue, the loop will continue to run. If it becomesFalse, the loop will stop.- Indentation: Like
ifstatements, the code inside the loop must be indented.
Example:
counter = 0
while counter < 5:
print(f"Counter is at {counter}")
counter += 1 # Increment the counter
How it works:
- The loop starts by checking the condition
counter < 5. - As long as
counteris less than 5, the code inside the loop runs. - After each loop,
counterincreases by 1. - Once
counterreaches 5, the condition becomesFalse, and the loop stops.
Common Mistakes: Infinite Loops
An infinite loop occurs when the condition in a while loop never becomes False. This will cause the loop to run forever, which is usually unintended.
Example of an Infinite Loop:
counter = 0
while counter < 5:
print(f"Counter is at {counter}")
# Forgot to increment counter, so the loop runs forever
In this case, the counter never increases, so counter < 5 is always True, creating an infinite loop. To avoid this, ensure that the condition can eventually become False.
For Loops
A for loop is used to iterate over a sequence (like a list, string, or range) and executes a block of code for each item in that sequence.
Basic Syntax:
for item in sequence:
# Code to run for each item
item: This is a variable that takes the value of each item in the sequence, one at a time.sequence: This can be a list, string, tuple, or any other iterable object.
Example:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(f"Number: {num}")
How it works:
- The
forloop goes through each item in thenumberslist. - For each iteration, the variable
numtakes the value of the current item, and the code inside the loop is executed.
Using Range() with For Loops
The range() function is often used with for loops to generate a sequence of numbers. It’s useful when you want to iterate over a specific range of values.
Example:
for i in range(5):
print(f"i is {i}")
How it works:
range(5)generates numbers from 0 to 4.- The loop runs 5 times, with
itaking values from 0 to 4.
You can also specify a start and an end in range():
for i in range(2, 6):
print(f"i is {i}")
This prints values from 2 to 5 (the end value is not included).
You can even specify a step value:
for i in range(0, 10, 2):
print(f"i is {i}")
This will print 0, 2, 4, 6, 8 by stepping through the range with increments of 2.
Break and Continue
1. Break:
The break statement allows you to exit a loop early, even if the loop’s condition is still True. This is useful when you want to stop the loop based on a specific condition.
Example:
for i in range(10):
if i == 5:
break # Exit the loop when i is 5
print(i)
In this case, the loop stops as soon as i equals 5, so only numbers 0 through 4 are printed.
2. Continue:
The continue statement skips the rest of the code inside the loop for the current iteration and moves to the next iteration.
Example:
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i)
This loop prints only odd numbers because the continue statement skips the even ones.
While vs For Loops: When to Use Them
- Use a
forloop when you know in advance how many times you want to loop (like iterating through a list or usingrange()). - Use a
whileloop when you want the loop to continue running as long as a certain condition isTrue. This is useful when the number of iterations isn’t known in advance.
Nesting Loops
When you place one loop inside another, it’s called nesting, and it’s helpful when working with multi-dimensional data or for complex tasks.
Example:
for i in range(3):
for j in range(2):
print(f"i = {i}, j = {j}")
How it works:
- The outer loop (
for i in range(3)) runs 3 times. - For each iteration of the outer loop, the inner loop (
for j in range(2)) runs twice.
Loops with Else
This may seem odd if you are coming from other computer languages, but in Python, a loop can have an else block!
The else block runs after the loop finishes its normal iterations, unless the loop is exited with a break statement.
Example:
for i in range(5):
print(i)
else:
print("Loop completed")
How it works:
- The
elseblock runs after theforloop finishes all iterations. - If the loop is interrupted by a
break, theelseblock will not run.
Example: Building a Simple Program
Let’s build a simple number-guessing game where the user has to guess a number between 1 and 10.
Number Guessing Game:
import random
# Generate a random number between 1 and 10
number_to_guess = random.randint(1, 10)
attempts = 0
while True:
guess = int(input("Guess the number (between 1 and 10): "))
attempts += 1
if guess == number_to_guess:
print(f"Congratulations! You guessed the number in {attempts} attempts.")
break
elif guess < number_to_guess:
print("Too low! Try again.")
else:
print("Too high! Try again.")
How it works:
- A random number between 1 and 10 is generated using the
random.randint()function. - The user is prompted to guess the number in a
whileloop that runs until the correct number is guessed. - The game gives feedback on whether the guess is too high or too low and tracks the number of attempts.
Key Concepts Recap
- While loops repeat as long as a condition is
True. - For loops iterate over a sequence of items or numbers.
- Use the
breakstatement to exit a loop early and thecontinuestatement to skip an iteration. - Nested loops are loops inside other loops.
- Loops can have an
elseblock that runs if the loop completes normally (withoutbreak).
Exercises
- Write a
whileloop that prints numbers from 1 to 10. - Create a
forloop that prints the square of each number in the list[1, 2, 3, 4, 5]. - Write a program that asks the user for a password and gives them 3 attempts to enter the correct password using a
whileloop. If they fail 3 times, print “Access denied.” - Use a nested
forloop to print a pattern of stars, such as:
*
**
***
****
*****
Next time, we’ll explore how you can work with tuples in Python!
FAQ
Q1: What’s the difference between a while loop and a for loop? When should I use each?
A1: The main difference is how they control repetition:
whileloop: It runs as long as a given condition remainsTrue. Use it when you don’t know in advance how many times the loop will need to run, but the loop is controlled by a condition.- Example: Waiting for a user to guess a correct number.
forloop: It iterates over a sequence (such as a list, string, or range) for a set number of times. Use it when you know exactly how many iterations you need, or when you’re working with collections like lists or ranges.- Example: Looping through each item in a list.
Q2: Why does my while loop run forever?
A2: A while loop runs as long as its condition is True. If the condition never becomes False, the loop will run indefinitely. This is called an infinite loop.
Common reasons for infinite loops:
- Forgetting to update a variable inside the loop (e.g., a counter that controls the condition).
- Having a condition that is always
True.
To fix it, make sure that:
- The condition can eventually become
False. - You update variables inside the loop that affect the condition.
Example of a fixed loop:
counter = 0
while counter < 5:
print(counter)
counter += 1 # Increment to avoid infinite loop
Q3: Can I use a for loop without using range()?
A3: Yes, you can use a for loop with any iterable object (e.g., lists, strings, tuples). range() is often used for numeric sequences, but it’s not necessary for non-numeric data.
Examples:
- List:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
- String (loops through each character):
word = "Python"
for letter in word:
print(letter)
Q4: What’s the difference between break and continue?
A4:
break: Exits the loop entirely, stopping all further iterations.- Use
breakwhen you want to end the loop immediately. continue: Skips the rest of the current iteration and moves to the next iteration of the loop.- Use
continuewhen you want to skip part of the loop and go to the next iteration without exiting the loop.
Example:
for i in range(5):
if i == 2:
continue # Skip the number 2
print(i)
This prints 0, 1, 3, 4 because 2 is skipped.
Q5: Can I use a for loop to count backward or loop over a sequence in reverse?
A5: Yes, you can use the range() function with a negative step to count backward in a for loop.
Example:
for i in range(5, 0, -1):
print(i) # Output: 5, 4, 3, 2, 1
Alternatively, to iterate over a list or string in reverse, use Python’s slicing syntax:
word = "Python"
for letter in word[::-1]:
print(letter) # Output: n, o, h, t, y, P
Q6: Why is the else clause in a loop not running when I use break?
A6: The else block in a loop runs only if the loop completes normally (i.e., it isn’t interrupted by a break statement). If you use break to exit the loop, the else block will not run.
Example:
for i in range(5):
if i == 3:
break
else:
print("Loop finished without break")
In this case, the else block will not run because the loop was interrupted by break when i == 3.
Q7: Can I change the value of the loop variable inside a for loop?
A7: While you can technically change the value of the loop variable inside a for loop, doing so won’t affect the next iteration of the loop. The loop variable is automatically updated by Python in each iteration based on the sequence or range().
Example (ineffective change):
for i in range(5):
print(i)
i = 10 # Changing i doesn't affect the loop
This prints 0, 1, 2, 3, 4 because Python still controls the loop variable (i), even though you assign it a different value inside the loop.
Q8: How can I run a For loop for a fixed number of iterations without using Range()?
A8: You can run a loop for a fixed number of iterations without using range() by iterating over a sequence of predefined values. For example, you can use a list or a repeated value:
# Use a list of repeated values
for _ in [None] * 5:
print("This runs 5 times")
Here, [None] * 5 creates a list with 5 elements, and the loop runs 5 times. The underscore (_) is used as a throwaway variable since you don’t need to use it.
Q9: Can I use a while loop and for loop together?
A9: Yes, you can nest a for loop inside a while loop or vice versa. This is useful when you need multiple levels of looping or when one loop’s condition depends on the other.
Example:
counter = 0
while counter < 3:
print(f"While loop iteration: {counter}")
for i in range(2):
print(f" For loop iteration: {i}")
counter += 1
This will first run the while loop, and for each iteration of the while loop, it will run the for loop twice.
Q10: What happens if I try to use else with a while loop that runs infinitely?
A10: In a while loop that never ends (due to an always True condition or an infinite loop), the else block will never run. The else block only executes after the loop condition becomes False or after the loop finishes its iterations (if it’s a for loop). In an infinite loop, since the loop condition never becomes False, the else block will be skipped.
Q11: How do I control how fast a loop runs?
A11: You can control the speed of a loop by adding a delay between iterations using the time.sleep() function from Python’s time module. This will pause the loop for a specified number of seconds between each iteration.
Example:
import time
for i in range(5):
print(i)
time.sleep(1) # Pause for 1 second
This loop prints one number every second.
Q12: Why is the last item in my range not included in the loop?
A12: The range() function in Python generates numbers starting from the first number up to (but not including) the last number. This is how range() works by design.
Example:
for i in range(5):
print(i)
This will print 0, 1, 2, 3, 4 but not 5, because range(5) generates numbers from 0 to 4.
