 While Loop
While Loop
While loop is another type of loops. It performs the same, but the construction of the loop differs.
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.
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 (
counterin 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!
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 moneylist.
- Set the condition if the counterequals100.
- Finish the program if the counterequals100.
- Add the moneyiterator to thecounter.
- Increase the iby1.
- Print the counter.
Lösung
Danke für Ihr Feedback!
single
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen
Awesome!
Completion rate improved to 2.08 While Loop
While Loop
Swipe um das Menü anzuzeigen
While loop is another type of loops. It performs the same, but the construction of the loop differs.
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.
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 (
counterin 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!
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 moneylist.
- Set the condition if the counterequals100.
- Finish the program if the counterequals100.
- Add the moneyiterator to thecounter.
- Increase the iby1.
- Print the counter.
Lösung
Danke für Ihr Feedback!
single