I'm practicing my while loop and general looping skills and have encountered a problem that has left me puzzled.
I'm trying to write a program that gives a price for a movie ticket based on the age of the user. The outer loop and first input statement handles the age to price part. After the user enters their age and a price gets returned for the first input, in the outer loop, they get asked using a second input in the inner loop if they have someone else who's attending. If the user answers no, I'm expecting the entire program to break. If the user answers yes, I'm expecting just the inner loop to break and the first loop to start again. If the user enters anything other than no or yes, I'm expecting the inner loop to start again.
The problem is in the second input statement in the inner loop when I enter 'no'. I'm expecting the entire program to break as it should for 'no', however, just the inner loop breaks which restarts the first loop.
while True:
age = input("Enter your age and the price of the movie will be displayed: ")
if age == 'quit':
break
elif int(age) < 3:
print("You're ticket price today is free.")
elif int(age) < 12:
print("You're ticket price today is $10. ")
elif int(age) <= 150:
print("You're ticket price today is $15")
elif int(age) > 150:
print("You've entered an invalid input. Please enter a valid age or type 'quit' to exit.")
else:
print("You've entered an invalid input. Please enter a valid age or type 'quit' to exit.")
while True:
repeat = input("Do you have someone else who's attending this movie? (yes/no): ")
if repeat.lower() == 'no':
break
elif repeat.lower() == 'yes':
break
else:
print("You've entered an invalid input. Please enter 'yes' to add someone or 'no' to quit.")
##Update 2
flag = True
while flag:
while True:
age = input("Enter your age and the price of the movie will be displayed: ")
if age == 'quit':
break
elif int(age) < 3:
print("You're ticket price today is free.")
elif int(age) < 12:
print("You're ticket price today is $10. ")
elif int(age) <= 150:
print("You're ticket price today is $15")
elif int(age) > 150:
print("You've entered an invalid input. Please enter a valid age or type 'quit' to exit.")
else:
print("You've entered an invalid input. Please enter a valid age or type 'quit' to exit.")
while True:
repeat = input("Do you have someone else who's attending this movie? (yes/no): ")
if repeat.lower() == 'no':
flag = False
break
elif repeat.lower() == 'yes':
break
else:
print("You've entered an invalid input. Please enter 'yes' to add someone or 'no' to quit.")
Use a flag variable as the outermost while condition, instead of while True
.
flag = True
while flag:
# do stuff
while True:
# do stuff
if somecondition:
# set flag=False so the outer loop will stop
flag = False
break