While Loop
While loop is another type of loops. It performs the same, but the construction of the loop differs.
99
1
2
3
4
5
6
7
8
9
10
# Summing all prices
prices = [3, 5, 6, 2, 7, 8]
i = 0
counter = 0
while i < len(prices):
counter += prices[i]
i += 1
print(counter)
12345678910# Summing all prices prices = [3, 5, 6, 2, 7, 8] i = 0 counter = 0 while i < len(prices): counter += prices[i] i += 1 print(counter)
When we want to stop our loop immediately, we need to use break.
9
1
2
3
4
5
6
7
8
9
prices = [1, 2, 3, 4, 5, 6]
i = 0
while i < len(prices):
if prices[i] == 4:
break
else:
print(prices[i])
i += 1
123456789prices = [1, 2, 3, 4, 5, 6] i = 0 while i < len(prices): if prices[i] == 4: break else: print(prices[i]) i += 1
We use a special variable (
counter
in our case) to collect elements of the price list (in our case). If you want to count the sum of the numbers from 1 to 10, you also have to create a variable that collects the sum after each iteration.
For more practice with loops try this course!
Uppgift
Swipe to start coding
Let's count all money from the list until the sum equals the 100!
- Set the while loop to work with the
money
list. - Set the condition if the
counter
equals100
. - Finish the program if the
counter
equals100
. - Add the
money
iterator to thecounter
. - Increase the
i
by1
. - Print the
counter
.
Lösning
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
money = [66, 12, 5, 17, 15, 2, 46]
i = 0
counter = 0
# Set the while loop to work with the money list
while i < len(money):
# Set the condition if the counter equals 100
if counter == 100:
# Finish the program
break
else:
# Add the money iterator to the counter
counter += money[i]
# Increase the i by 1
i += 1
# Print the counter
print(counter)
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 2. Kapitel 6
single
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
money = [66, 12, 5, 17, 15, 2, 46]
i = 0
counter = 0
# Set the while loop to work with the money list
___ i < ___:
# Set the condition if the counter equals 100
if ___ == ___:
# Finish the program
___
else:
# Add the money iterator to the counter
counter += ___[i]
# Increase the i by 1
___ += 1
# Print the counter
print(___)
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal