The while loop in Python
The peculiarity of the while
loop is that it will be executed as long as the expression passed to it is true.
Its syntax looks like this:
while expression is true:
'''
code that executes until
the condition becomes false
'''
In the while
loop condition, you need to use dynamically changing values, such as a counter, otherwise you may get infinite output to the console. Let's set the loop to run while the counter is less than 5
:
i = 0
while i < 5:
i += 1
print(i)
Result of code execution:
1
2
3
4
5
Use the while
loop to print numbers from 1
to 10
to the console.
Use the while
loop to print numbers from 100
to 1
to the console.
Use the while
loop to print odd numbers from 1
to 100
to the console.