This is probably a simple answer but I thought I'd ask anyway.
My code below is asking the user for a number and depending on the answer provided will print the grade that corresponds with the numbers.
I want to stop the loop (terminate the program) by having the user type in (999). I know the problem is in my if userScore >= 90" print ('A')
. So when the user enters the 999, the computer takes it as an A.
Is there a shortcut to fix this?
(PS I added the breaks to every line because when they were not there the outputs kept repeating endlessly.)
userScore = float(input('Enter the score or type "999" to quit: '))
while True:
try:
if userScore >= 90:
print ("You earned an A")
break
elif userScore >= 80:
print ("You earned a B")
break
elif userScore >= 70:
print ("You earned a C")
break
elif userScore >= 60:
print ("You earned a D")
break
elif userScore <= 59.9:
print ("You earned an F")
break
except:
if userScore == '999':
break
main()
Don't use try except. Try except is meant for error handling. This can be handled using a simple while loop.
userScore = float(input('Enter the score or type "999" to quit: '))
while userScore!=999:
if userScore >= 90:
print ("You earned an A")
break
elif userScore >= 80:
print ("You earned a B")
break
elif userScore >= 70:
print ("You earned a C")
break
elif userScore >= 60:
print ("You earned a D")
break
elif userScore <= 59.9:
print ("You earned an F")
break
main() # Why is this even required?
Here is what you are trying to accomplish. It is explained in the comments.
while True:
#This part gets the user input. It waits until the user enters a valid number input.
while True:
prelim = input('Enter the score or type "999" to quit: ')
try:
prelim = int(prelim)
except:
print("Please enter a valid input.")
else:
#if the input can be converted into a number, then this is our final input value
userScore = float(prelim)
break
#The first thing we should check is if the user wants to exit. This way it won't print out an answer then exit.
if userScore == 999:
break
if userScore >= 90:
print ("You earned an A")
elif userScore >= 80:
print ("You earned a B")
elif userScore >= 70:
print ("You earned a C")
elif userScore >= 60:
print ("You earned a D")
elif userScore <= 59.9:
print ("You earned an F")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.