10while Loops
In the previous chapter, you learned how to repeat actions in Python using a for
loop. However, what should you do if you want your loop to keep repeating while a condition is true? Get ready to learn about Python's other loop, the while loop!
Create a while Loop
Suppose you have a variable x
that decreases each time a loop is completed. With each decrease, the string "x is greater than 0"
is printed until x
is equal to the value 0
. How would you go about setting this up? You could use a while
loop!
A while
loop repeats (or iterates) all actions indented underneath the while
loop so long as the condition you define is true. Let's use a while
loop to set up the previous logic for the variable x
.
>>> x = 5
>>> while x> 0:
print("x is greater than 0")
x -= 1
x is greater than 0
x is greater than 0
x is greater than 0
x is greater than 0
x is greater than 0
In the previous code, the variable x
is assigned the value 5
. This value is where the while
loop starts to count down. Just below the variable assignment, the while
loop logic begins with the condition “while x
is greater than 0
.” What this means is that while the value of x
is more than 0, the action inside the while
loop happens. In this case, a string is printed, and the value of x
is decreased by 1.
As you can see, the string is printed five times given that x
is greater than 0 for five of the loops ...
Get Bite-Size Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.