An iteration or loop is the repetition of a sequence of instructions or statements performed until a certain condition is reached.
These are used in complex calculations or projects that required a block of code to be performed more than once based on certain conditions that will be stopped based on the program.
An example of a while loop is this:
Code:
Output:
To walk you through the code above
It starts by assigning the integer 10 to the variable number.
The next line shows the use of the statement which can be read as "while number is not equal to 10, run this program"
The program will print "No" until the condition is reached
And the final line, which increments the number( number+=1 is also the same as number =number +1)
This is done to get the program to run for a finite number of time and avoid an infinite loop
An Infinite loop is a program in a loop that will keep running endlessly cause there is no increment or decrement made to ensure the number gets to a specified value to stop
An infinite loop can be created from the code above by removing the last line:
Code:
Output:
Or a simple infinite loop like
While(True):
Print("yes")
To perform a more flexible program
The if statement and be added in a while loop
Code:
Hope you enjoyed this lesson and learned from it
Read, like, share, comment, and see you in the next lesson
Top comments (0)