Computers are often used to automate repetitive tasks. Python has two types of loops that can be used to execute instructions repeatedly: the for loop and the while loop.
The for loop
The for loop is useful for iterating over a sequence.
Here is a simple program that prints each number in a list and then prints “Done!”
Here is the basic structure of a for loop. Note the indentation used to indicate the instructions that should be repeated.
for<variable> in <sequence>:
<body: code to be repeated for each element in the sequence>
<code to run after iterating through the sequence>
The body will be run once for each element in the sequence. In the body, you can refer to the current element using the name of the variable you provide between the for and the in.
The while loop
The while loop is used to repeatedly execute instructions as long as a boolean condition is met.
Here is a simple program that uses a while loop to count down from 5 and then prints “Blastoff!”