The while loop in Python allows you to execute a block of code repeatedly as long as a certain condition is true. The syntax for a while loop is as follows:
while condition:
# block of code
The block of code will be executed as long as the condition
is true. Once the condition
becomes false, the program will move on to the next line of code after the while loop.
Example - Counting with a While Loop
One common use case for a while loop is to count up to a certain number. Here's an example:
count = 1
while count <= 5:
print(count)
count += 1
In this example, we initialize the count
variable to 1
. Then, we enter a while loop with the condition count <= 5
. As long as count
is less than or equal to 5
, the block of code will execute.
Inside the block, we print the current value of count
and then increment it by 1 using the +=
operator. When count
becomes 6, the condition becomes false and the program exits the while loop.
The output of this program will be:
1
2
3
4
5
Example - User Input with a While Loop
Another use case for a while loop is to repeatedly ask the user for input until they provide a valid response. Here's an example:
name = ""
while not name:
name = input("What is your name? ")
print("Hello, " + name + "!")
In this example, we initialize the name
variable to an empty string. Then, we enter a while loop with the condition not name
. As long as name
is an empty string, the block of code will execute.
Inside the block, we use the input()
function to ask the user for their name. If the user enters a non-empty string, the condition not name
becomes false and the program exits the while loop.
Finally, we print a greeting message using the name
variable.
The output of this program will depend on the user's input.
Explore Other Related Articles
Python For Loops, Range, Enumerate Tutorial
Python if-else Statements Tutorial
Python set tutorial
Python tuple tutorial
Python Lists tutorial
Top comments (0)