Python - 7
Python - 7: Loops
Loops repeat code without making you write the same lines again and again.
Your challenge: Use a for loop to repeat a message, then use another loop to print numbers.
Repeat code with for
A loop like: for i in range(5): runs the indented code five times.
The variable i changes each time through the loop.
Use range()
range(5) produces: 0, 1, 2, 3, 4
So this code prints those numbers: for number in range(5):
Indentation matters
Just like an if statement, the code inside a loop must be indented.
Try it: Change range(5) to range(10) and see how many times the loop runs.
Good Python habit: Use a meaningful loop variable such as number when the value has a clear purpose.
👀 Show Example Solution
for i in range(5):
print("Hello!")
for number in range(5):
print(number)
for number in range(3):
print("Python is fun!")Each loop repeats its indented code once for every value produced by range().
