This tutorial provides an introduction to using while loops in Python. It explains the basic syntax of a while loop and demonstrates how to use it to execute code repeatedly based on a given condition. The tutorial also covers how to use the
continue statements to modify the behavior of a while loop.
A while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition.
The basic syntax is:
while condition: # code to be executed
The code in the loop will continue to be executed as long as the condition is
True. When the condition becomes
False, the loop will terminate.
Here is an example of a simple while loop that counts from 1 to 5:
count = 1 while count <= 5: print(count) count += 1
This will output:
1 2 3 4 5
It’s important to include a way to modify the condition in the loop, otherwise, it will become an infinite loop. In the example above, we are incrementing the value of
count by 1 each time the loop iterates, eventually causing the condition to become
count is greater than 5.
You can also use the
continue statements in a while loop.
break will terminate the loop, and
continue will skip the rest of the current iteration, and move on to the next one.
Here is an example of using
break it to exit a loop when a certain condition is met:
while True: user_input = input("Enter a number: ") if user_input == "q": break else: print("You entered:", user_input)
This will continue to ask the user to enter a number until they enter the letter
q, at which point the loop will terminate.
And here is an example of using
continue to skip the rest of the current iteration if a certain condition is met:
count = 0 while count < 10: count += 1 if count % 2 == 0: continue print(count)
This will output the odd numbers from 1 to 9, because the
continue statement causes the loop to skip the rest of the current iteration when
count is even.