While Loop Extended
while True:
print("You are in a corridor, do you go left or right?")
direction = input("> ")
if direction == "left":
print("You have fallen to your death")
break
The continue command stops executing code in the loop and starts at the top of the loop again. Essentially, we want to kick the user back to the original question.
while True:
print("You are in a corridor, do you go left or right?")
direction = input("> ")
if direction == "left":
print("You have fallen to your death")
break
elif direction == "right":
continue
else:
print("Ahh! You're a genius, you've won")
The else statement refers to any input besides left or right (up or esc). Since the user is a winner, we do not want to use break or it would say they have failed.
Proceed to the Nearest Exit
The exit() command completely stops the program and it will not run any more lines of code.
lets have an example
while True:
print("You are in a corridor, do you go left or right?")
direction = input("> ")
if direction == "left":
print("You have fallen to your death")
break
elif direction == "right":
continue
else:
print("Ahh! You're a genius, you've won")
exit()
print("The game is over, you've failed!")
another example :-
print("Let's play chutes and ladders. Pick ladder or chute.")
while True:
print("Do you want to go up the ladder or down the chute?")
direction = input("> ")
if direction == "chute":
print("Game over!")
break
elif direction == "ladder":
continue
else:
print("Game over!")
exit ()
print("Thanks for playing!")
problem solving :-
You are going to use a while loop and some of the concepts from the past few days.
1.Start by picking a number between 0 and 1,000,000. This will be your first variable.
2.Create a while loop to keep asking the user to guess your number.3.If they are too low, tell them "too low." If they guess too high tell, them "too high."
4.If the user guesses correctly, tell them they are a winner (maybe add a fun emoji too!)
5. Count the number of attempts it took for the user to guess number. Make sure you only show that after they get the answer correct.
5. Count the number of attempts it took for the user to guess number. Make sure you only show that after they get the answer correct.
print ("One million to one")
print("")
guees_N = 89456
count = 0
while True:
count += 1
oneTime = int(input("Guess your number to match:"))
if oneTime == guees_N :
print("Correct")
break
elif oneTime > 0 and oneTime > guees_N and oneTime-guees_N >= 5001 :
print("too high")
continue
elif oneTime > 0 and oneTime > guees_N and oneTime-guees_N <= 5000 :
print("high")
continue
elif oneTime >0 and oneTime < guees_N and guees_N - oneTime >= 5000 :
print("too low")
continue
elif oneTime > 0 and oneTime < guees_N and guees_N - oneTime <= 5000 :
print("low")
continue
elif oneTime < 0:
print("I don't want to play anymore")
exit()
print("till run total guess",count)