In programming, loops allow you to repeat a block of code a number of times.
If there's a question like the one to the right, how many tries will it take to guess?
1 guess? 2 guesses? 4 guesses? 100 guesses?
For times when a block of code needs to run an uncertain or non-specific amount of times, you use a while loop.
You use a control variable to set when your loop does and doesn't run. If you want your loop to repeat until a user guesses correctly, use a boolean control variable.
Make a new project.
Add:
guessed = FalseThe loop repeats until a condition you set is met in what is called a conditional statement. Use your loop type and the control variable here.
Set the condition of the loop to run while guessed is not true:
while not guessed:The body of the loop is the code that will run repeatedly.
Add the following code inside your while loop:
guess = input("Pick a number")
if int(guess) == 14:
guessed = True
print("You win!")
The print statement will only run after the loop has ended.
Here's what your project could look like at this point:
guessed = FalseUse while loops when a program must run an unknown amount of times. While loops are made of a loop control variable (made first), a conditional statement (the conditions that must be met for the loop to run), and a loop body (the actual code that will run).
while not guessed: guess = input("Pick a number") if int(guess) == 14: guessed = True
print("You win!")
- Update the code to handle entries with different capitalizations.
- Add code to make the guess input statement easier to understand for the user.
