The while statement
The while statement in Python is a loop statement that allows you to execute a block of code repeatedly while a certain condition is true. The syntax of the while statement is as follows:
vbnet
while condition:
# code to be executed while the condition is true
The while loop will continue to execute the code inside the block as long as the condition is true. If the condition becomes false, the loop will terminate and the program will continue to the next statement after the loop.
It is important to make sure that the condition will eventually become false, otherwise, the loop will continue to run indefinitely, which can cause the program to hang or crash.
Here is an example of using the while statement to print out the numbers from 1 to 5:
css
i = 1
while i <= 5:
print(i)
i += 1
This will output:
1
2
3
4
5
It is also possible to use the break and continue statements inside a while loop to break out of the loop or skip certain iterations based on certain conditions. For example:
less
i = 1
while i <= 10:
if i == 5:
break
if i % 2 == 0:
i += 1
continue
print(i)
i += 1
This will output:
1
3
7
9 Since the loop is terminated when i == 5, and the even numbers are skipped using the continue statement.
Apply for Python Certification!
https://www.vskills.in/certification/certified-python-developer