Loop Repeats the Line
A for loop repeats the lines that are indented under it. range(3) means "three times". The code below shows Hi three times. Change the text so the program…
Loops repeat code multiple times.
FOR loop - for a specific number of times:
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
range(5) gives numbers from 0 to 4.
range(1, 6) gives numbers from 1 to 5.
WHILE loop - while condition is true:
count = 0
while count < 3:
print(count)
count = count + 1 # or count += 1
A for loop repeats the lines that are indented under it. range(3) means "three times". The code below shows Hi three times. Change the text so the program…
range(3) counts from 0: it gives 0, 1, 2. To choose where to start and where to stop, give range two numbers: range(start, stop). It stops BEFORE stop, so…
Use a for loop to print numbers from 1 to 5. Each number on a new line.
Use a for loop to print "Hello" exactly 3 times.
Calculate the sum of numbers from 1 to 10 using a loop. Store result in 'total' and print it. Expected result: 55
A while loop repeats while its condition is true. Here the last line is unfinished: the counter n must grow by 1 on every pass, otherwise the loop would never…
Use a while loop to print numbers from 1 to 5.
Learn to repeat actions using loops.
This lesson has 7 exercises.
No. The code is written and run in the browser.