Pythonbeginner 8 min
Repeat actions with for and while, and use range to count.
How to repeat code with for and while loops and generate numbers with range().
Looping over names, adding up prices or retrying until something works are everyday tasks. A loop lets you write the instruction once.
A for loop goes through a sequence, one item at a time. range(n) produces the numbers 0 up to (but not including) n.
range(start, stop) begins at start: range(1, 4) gives 1, 2, 3.
A while loop keeps going as long as its condition is True. Make sure something inside the loop eventually makes the condition False, or it never stops.
break leaves a loop early and continue skips to the next round.
range(1, 4) yields 1, 2, 3 so the first loop prints Round 1, Round 2, Round 3.n to total each round: 1, 3, 6, 10, 15, then n becomes 6 and the loop ends.Sum 1 to 5 is 15.APPLE, BANANA, CHERRY.Change the first loop to count from 1 to 10 and print only the even numbers. Hint: i % 2 == 0.
range(5) stops at 4, not 5.for / while.for item in sequence: visits each item; range() makes number sequences.while condition: repeats until the condition is False.break and continue control the flow inside loops.You finished the Python beginner section. Next: functions, lists and dictionaries.
for i in range(3):
print(i) # 0, 1, 2for i in range(1, 4):
print("Round", i)
total = 0
n = 1
while n <= 5:
total = total + n
n = n + 1
print("Sum 1 to 5 is", total)
for fruit in ["apple", "banana", "cherry"]:
print(fruit.upper())