Both loops repeat steps. A for loop is for a known number of repeats or a collection. A while loop is for repeating until something changes. This note shows how to choose, and how to avoid a loop that never ends.
You have two loops in Python, and each one is the better tool for a different job.
Do I know how many times to repeat, or what to go through?
for. Go through every item of a list, count from 1 to 10, or repeat a fixed number of times.while. Repeat until something happens: the user types the right password, a number gets small enough, or a game ends.A while loop needs something inside it that changes the condition. If nothing changes, the loop never ends. This is called an infinite loop. In the loop above, the line savings = savings * 2 is what finally makes savings < 100 false.
Three habits keep you safe:
while loop, say which line changes the condition.while loop.while when for is simpler. Going through a list is a job for for.for loop goes through it. Make a copy or build a new list.Write your answers in full sentences. Try each one before you read the pointers.
count = 1 and then while count < 5: with only a print(count) inside. Explain why it never stops, and give the one line that fixes it.while loop. Can you write it with a for loop? What would you need to add, and why is while a more natural fit?n = 3, then while n > 0: print n and subtract 1 from n, and after the loop print "go". Then change "subtract 1" to "subtract 2" and trace it again.while is better than for because it is more powerful." Give your opinion, and give one case in which for is clearly the better choice.for, because you know it is 10 times. (b) while, because you do not know how many tries. (c) for, because you go through a list. (d) while, because you do not know how many halvings.count, so count < 5 stays true. Add the line count = count + 1.break when the savings reach 100. This is awkward, because you do not know the number of days in advance.n becomes -1 and the loop stops, so it prints 3, 1, go.while can do any for job, but a for loop is shorter and safer for a list, because it cannot run forever.Log in to join the discussion.
Loading…