Using "while" Loops
Loops are necessary when we need to perform a set of operations several times. The first type of loop we will discuss is called the while loop. The while loop checks a logical condition like the if statement. If the condition is true, the code inside the while loop will execute until the condition being checked becomes false. Run this code in Repl.it:
avalue= int(input('Please enter the number 10: ')) while (avalue != 10): print('Your input value is not equal to 10') print('Please try again: ') avalue= int(input('Enter the number 10: ')) print('Thank you') print('You entered a value of 10')
This while loop checks to see if the value input was equal to 10. If not, the while loop will continue to execute the indented code until a value of 10 is input. The syntax rules are similar to those of the if statements:
- The logical expression following the "while" must end with a colon (:)
- The code to be executed if the logical condition is satisfied must be indented.
- Indentation is how Python knows you have a group of commands inside the while statement Indentation can be accomplished in Repl.it using the "tab" key. In the Repl.it editor, this is equivalent to typing two spaces. Some Python editors prefer four spaces for indentation.
Make sure you run the examples provided in Repl.it. When we execute the code within a loop over and over again, the process is known as iteration.
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/ This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 License.