Intermediate âĸ Python
Loops
đ For Loops
A for loop repeats code for each item in a sequence. The range() function is commonly used when we want to repeat something a certain number of times.
for i in range(5):
print(i)0 1 2 3 4
đ Everything in Loops
Make Python repeat tasks automatically. Here is every step in this topic in one place, so you can review what you learned or jump straight to a step.
đ For Loops
A for loop repeats code for each item in a sequence. The range() function is commonly used when we want to repeat something a certain number of times.
for i in range(5): print(i)âģī¸ While Loops
A while loop continues running as long as its condition is True. It is important to change the value used by the condition so that the loop can eventually stop.
count = 1 while count <= 3: print(count) count += 1đĸ Using range()
The range() function creates a sequence of numbers. range(5) gives the numbers 0 through 4. The ending number is not included.
for number in range(5): print(number)đĸ Repeating a Message
Loops are useful when we want to repeat the same action many times. Instead of writing the same print statement repeatedly, we can use a loop.
for i in range(3): print("Python is fun!")đļ Counting with a Step
range() can take three numbers: a start, a stop, and a step. The step tells Python how much to jump each time. range(2, 11, 2) starts at 2, jumps by 2, and stops before reaching 11.
for number in range(2, 11, 2): print(number)đ Counting Down
If we use a negative step, range() counts backwards. range(5, 0, -1) starts at 5 and goes down by 1 each time, stopping before it reaches 0. This is perfect for a rocket countdown!
for number in range(5, 0, -1): print(number) print("Blast off!")đ Looping Through a List
A for loop can go through every item in a list, one at a time. Each time the loop runs, the loop variable holds the next item from the list. This means we do not need to know how many items the list has.
pets = ["cat", "dog", "fish"] for pet in pets: print("I love my", pet)â Adding Up with a Loop
Loops can help us add up lots of numbers. We start with a total of 0, and each time the loop runs we add the next number to the total. After the loop finishes, we print the final total.
total = 0 for number in range(1, 6): total += number print(total)âąī¸ Stopping a While Loop
A while loop keeps going until its condition becomes False. In a countdown, we take 1 away from the counter each time. When the counter reaches 0, the condition countdown > 0 is False and the loop stops. If the counter never changed, the loop would run forever!
countdown = 3 while countdown > 0: print(countdown) countdown -= 1 print("Go!")
