Loops: Repeat Actions
6. While Loops
A while loop repeats instructions as long as a condition is true.
counter = 0
while counter < 5:
print(counter)
counter = counter + 1
Output:
0
1
2
3
4
Robotics example:
while True:
print("Robot is running")
Important: while True creates an infinite loop. The program continues running until it is interrupted or reset.
7. For Loops
A for loop repeats instructions for each item in a sequence or collection.
It is useful when you know how many times you want to repeat an action.
for number in range(5):
print(number)
Output:
0
1
2
3
4
You can also repeat an instruction a specific number of times:
for i in range(3):
print("Hello Robot!")
8. for – Understanding range()
The range() function generates a sequence of numbers.
It is commonly used with for loops.
Three ways to use range():
for i in range(5): # From 0 to 4
print(i)
for i in range(1, 6): # From 1 to 5
print(i)
for i in range(0, 11, 2): # From 0 to 10, counting by 2
print(i)
The general syntax is:
range(start, stop, step)
| Parameter | Description |
|---|---|
| start | First number (default is 0) |
| stop | Ending limit (not included) |
| step | Amount to increase or decrease |
