Two types of loop in Python

In Python we have two types of loops:

while loop: executes a block of code as long as the loop's expression is True.

while <condition>:# loop body# loop body# statements to execute when condition # becomes False

for loop: a counted loop, executes a block of code n times

for variable in container:# Loop body# Loop body# Statements to execute after the for loop # is complete

Let's start with while loops:

.

.

.


.

.

.

.

.

.

.

.

.

.


.

.

.

.

.


Let's talk about while loops. 

x = int(input("Enter a positive integer:")) while x > 0: print("***") x = x 3 print("the end") # enter a positive integer: 7

x = int(input("Enter a positive integer:")) while x > 0: print("***") x = x 3 print("the end") # enter a positive integer: 7
x = 7
*** x = 4 *** *** x = 1 *** *** *** x = -2 *** *** *** the end

x = int(input("Enter a positive integer:")) while x > 0: print("***") x = x 3 print("the end")

Each execution of the loop body is called an iteration, and looping is also called iterating


While loops: common errors

An infinite loop is a loop that will always execute because the loop's expression is always True. 

A common error is to accidentally create an infinite loop by assuming equality will be reached.

x = int(input("Enter a positive integer:")) while x = 0: # x = 7, 4, -1, -4, .... print("***") x = x 3 print("the end")


Source: Natalia Novak, https://academicworks.cuny.edu/bx_oers/36/
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 License.

Last modified: Friday, 4 March 2022, 3:25 PM