Understanding Python Loops: For and While Statements
Python provides two primary loop structures: for loops and while loops.
- For loops iterate over sequences (like lists, tuples, or strings), executing a code block for each element. The loop ends after all elements have been processed.
- While loops repeat a code block as long as a specified condition remains true. The loop terminates when the condition becomes false.
Python also includes control keywords like break and continue:
breakexits the current loop entirely.continueskips the remaining code in the current iteration and proceeds to the next one.
These tools offer flexibility for implementing repetitive tasks in Python programs.
While Loop Syntax
The basic structure of a while loop is:
while condition:
statements
Indentation and colon are esssential. Python does not have a do...while construct.
Example: Summing Numbers from 1 to 100
target = 100
total = 0
current = 1
while current <= target:
total += current
current += 1
print(f"Sum from 1 to {target} is: {total}")
Output:
Sum from 1 to 100 is: 5050
Infinite Loops
An infinite loop occurs when the condition never becomes false. This is useful for continuous operations, like server requests.
value = 1
while value == 1: # Always true
user_input = int(input("Enter a number: "))
print(f"You entered: {user_input}")
print("Loop ended.")
Press CTRL+C to interrupt an infinite loop.
While Loop with Else Clause
An else block executes after the loop finishes, but not if the loop is terminated by break.
counter = 0
while counter < 5:
print(f"{counter} is less than 5")
counter += 1
else:
print(f"{counter} is not less than 5")
Output:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
Single-Statement While Loops
If the loop body contains only one statement, it can be written on the same line:
active = True
while active: print("Looping...")
print("Done.")
For Loop Syntax
for loops iterate over iterable objects:
for element in sequence:
statements
Example: Iterating Over a List
websites = ["Baidu", "Google", "Huawei", "Taobao"]
for site in websites:
print(site)
Output:
Baidu
Google
Huawei
Taobao
Example: Iterating Over a String
text = "hello,world!"
for char in text:
print(char)
For Loop with Else Clause
Similar to while, an else block runs after the loop completes, unless break is used.
for num in range(6):
print(num)
else:
print("Loop finished.")
Output:
0
1
2
3
4
5
Loop finished.
Example with Break
companies = ["Baidu", "Google", "Huawei", "Taobao"]
for company in companies:
if company == "Huawei":
print("Found Huawei!")
break
print(f"Processing {company}")
else:
print("No Huawei found.")
print("Search complete.")
Output:
Processing Baidu
Processing Google
Found Huawei!
Search complete.
Using the range() Function
range() generates number sequences for iteration.
Basic Usage
for i in range(5):
print(i)
Output:
0
1
2
3
4
Specifying Start and End
for i in range(5, 9):
print(i)
Output:
5
6
7
8
Using a Step Value
for i in range(0, 10, 3):
print(i)
Output:
0
3
6
9
Negative Steps
for i in range(-10, -100, -30):
print(i)
Output:
-10
-40
-70
Iterating with Indexes
items = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ']
for index in range(len(items)):
print(index, items[index])
Output:
0 Google
1 Baidu
2 Runoob
3 Taobao
4 QQ
Creating Lists with range()
number_list = list(range(5))
print(number_list)
Output:
[0, 1, 2, 3, 4]
Break and Cnotinue Statements
Break in While Loop
value = 5
while value > 0:
value -= 1
if value == 2:
break
print(value)
print("Loop terminated.")
Output:
4
3
Loop terminated.
Continue in While Loop
value = 5
while value > 0:
value -= 1
if value == 2:
continue
print(value)
print("Loop ended.")
Output:
4
3
1
0
Loop ended.
Continue in For Loop
for char in "hello,world!":
if char == "e":
continue
print(f"Current character: {char}")
counter = 10
while counter > 0:
counter -= 1
if counter == 5:
continue
print(f"Counter value: {counter}")
print("Execution complete.")
Break in For Loop
for char in "Hello,World":
if char == "e":
break
print(f"Current character: {char}")
counter = 10
while counter > 0:
print(f"Counter value: {counter}")
counter -= 1
if counter == 5:
break
print("Process finished.")
Prime Number Example
for number in range(2, 10):
for divisor in range(2, number):
if number % divisor == 0:
print(f"{number} equals {divisor} * {number // divisor}")
break
else:
print(f"{number} is a prime number")
Output:
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
Pass Statement
pass is a null operation used as a placeholder.
Example in Loop
while True:
pass # Wait for keyboard interrupt (Ctrl+C)
Minimal Class Definition
class EmptyClass:
pass
Using Pass in a Loop
for char in "Runoob":
if char == "o":
pass
print("Pass block executed")
print(f"Current character: {char}")
print("Done.")
Output:
Current character: R
Current character: u
Current character: n
Pass block executed
Current character: o
Pass block executed
Current character: o
Current character: b
Done.