Loops: for and while
for loops
Computers are great at repeating work. Sending a message to 500 customers, adding up 10,000 sales, checking every product's stock - you write the instructions once and a loop repeats them for every item. Without loops, you'd copy the same lines again and again.
A for loop goes through each item in a list, string or range.
Read it like English: "for each item in this list, do this". In each round, the variable (item) holds the next value. The indented lines are the body of the loop - they run once per item. When the items run out, the loop ends and Python continues with the next unindented line.
range(start, stop) gives numbers from start up to (not including) stop:
range is useful when you want to repeat something a fixed number of times, or need counting numbers. range(5) gives 0, 1, 2, 3, 4 (five numbers, starting at 0). range(1, 11) gives 1 to 10.
while loops
A while loop repeats as long as a condition is true.
Use for when you know what to go through (a list, a range). Use while when you don't know how many rounds you need - for example, "keep asking until the user types a valid PIN". Always make sure something inside a while loop eventually makes the condition false, or the loop will run forever.
break and continue
continue skips the rest of this round and goes to the next item - useful for ignoring bad data. break stops the loop completely - useful when you've found what you were looking for, so there's no need to check the rest.
enumerate(list) when you need the position too: for i, item in enumerate(cart):forrepeats code for each item in a list, string or range.whilerepeats as long as a condition is true - make sure it ends.continueskips one round;breakstops the loop.
