In this lesson we will study indefinite loop in Python, that is loops where the number of iterations is not known at the beginning of the loop.
Let’s take some examples to better understand what is meant by an indefinite cycle.
Indefined loop in Python – first example
Insert integers and add them, exit the program when entering the zero value.
First we ask you to enter an integer n as input. After we set the variable sum equal to n and we carry out a loop to insert the other numbers and add them.
We set the condition n! = 0 in the while so as to stop the loop only if the value zero is entered.
Finally we display the sum obtained.
Here is the complete code on indefined loop in Python:
print('Enter numbers, enter 0 to finish!') n = int(input('Insert a number: ')) sum = n while n != 0: n = int(input('Insert a number: ')) sum += n print('The sum is: ', sum)
As you may have noticed, this time the cycle will end when we decide to stop, by entering the number 0 in this case. You may need to enter any other value.
Test the code in the online Python compiler in that link: Python compiler online.
Indefined loop in Python – Second example
Add whole numbers, stop when the sum reaches or exceeds 100.
This time it is not necessary to enter a number in input. So let’s set the sum to zero.
After we insert in the while loop the sum condition <100 and then we ask to insert a number n that we will add from time to time.
Here is the complete code:
sum = 0 while sum <100: n = int(input('Insert a number:')) sum += n print ('The sum is: ', sum)
In the next few lessons we will talk more about indefinite loop in Python.