Python Programming Language
Loops in Python
By Mark Ciotola
First published on October 10, 2019. Last updated on February 16, 2020.
Computers tend to be great at repetitive tasks. Further, repetitive tasks are relatively easy to program. You write code for the task once, then you place that task in a loop. A loop will try to repeat itself forever, but you usually don’t want that. So you write a control structure with a condition statement. Either the loop will run while the condition is true, or it will stop when the condition is true, depending on how the structure is written.
Below is a conditional loop statement. It will continue to increase the production until the step variable has reached the value of 10. The step +=1 increases the step variable by 1 each time this loop runs.
# Initialize variable production = 1.0 step = 1 # Run loop while(step < 10): # Condition statement production = production * 2.5 print 'Production =', production step += 1
Activity
- Write and run the above program.
- Modify the program to run for exactly 30 steps.
Leveling Up
- Write a loop within a loop. This is a common programming practice. For example, the top level loop might run a calculation that occurs for each country, while the second level loop might run a calculation that occurs for each province to state.
Further Reading
- Python While Loops (W3schools)
- Python For Loops (W3schools)