05: Bucle
Repeat actions with for and while loops. Control the flow with break and continue.
python
for
while
loops
break
continue
range
Lesson 05 · Loops¶
What you'll learn
- The
forloop withrange() - The
whileloop - The
breakandcontinuestatements - Nested loops
The for loop¶
for repeats a block of code for each element in a sequence:
Output:
The range() function¶
| Call | Generated values |
|---|---|
range(5) |
0, 1, 2, 3, 4 |
range(1, 6) |
1, 2, 3, 4, 5 |
range(0, 10, 2) |
0, 2, 4, 6, 8 |
range(10, 0, -1) |
10, 9, 8, ..., 1 |
# Count from 1 to 10
for i in range(1, 11):
print(i)
# Even numbers from 2 to 20
for i in range(2, 21, 2):
print(i)
# Count down
for i in range(5, 0, -1):
print(i)
print("Start!")
for over a string¶
The while loop¶
while repeats a block as long as a condition is true:
Output:
Infinite loop
If you forget to update the variable, the loop never ends:
Stop the program withCtrl+C.
while for input validation¶
answer = ""
while answer != "yes" and answer != "no":
answer = input("Did you understand? (yes/no): ")
print("Thank you!")
break — forced exit from the loop¶
continue — skip to the next iteration¶
Nested loops¶
A loop inside another loop:
Output:
Exercises¶
Exercise 1 — Sum from 1 to N¶
Ask for a number N and calculate the sum 1 + 2 + ... + N.
Solution
Exercise 2 — Prime numbers¶
Display all prime numbers smaller than 50.
Solution
Exercise 3 — Guess the number¶
Generate a "secret" number (hardcoded) and let the user guess with feedback.
Solution
Mini-project: Multiplication table¶
Display the multiplication table for numbers 1–10 in a tabular format.
Output (first rows):
Solution
{i*j:4} formats the number across 4 characters for alignment.
Summary¶
for i in range(n):— repeatntimesrange(start, stop, step)— generate sequences of numberswhile condition:— repeat as long as the condition is truebreak— forced exit from the loopcontinue— skip to the next iteration- Indentation is mandatory!
Next step: → Lesson 06: Lists