While Loops in Python

In Python, a while loop is used to repeatedly execute a block of code as long as a given condition remains True. It is useful when you don't know in advance how many times the loop should run.

How While Loops Work

1. The condition is evaluated before each iteration

2. If the condition is True, the loop body executes

3. After executing the loop body, the condition is checked again

4. If the condition is still True, the loop continues

5. If the condition becomes False, the loop stops

For Example:

correct_pin = "1234"

while True:

user_pin = input("Enter your PIN: ")

if user_pin == correct_pin:

print("Access granted!")

else:

print("Incorrect PIN. Try again.)


The code above asks the user the enter a pin and the program keeps continuing until the correct pin is entered with the help of a while loop

If you want a better understanding of while loops you can click the link below to watch a video about while loops in python

https://youtu.be/phsdV1cMDTA?si=51hAL9vG1UFv6eWa

Challenge (optional)

Make a program that asks the user to enter the most rare fruit in the world in a while loop and keeps asking them until they get it right!

r


⏳ Loading...