Python Python Basics All Together Now Handle Exceptions

Deonte Meriwether
Deonte Meriwether
1,513 Points

Raise value error

My code is looping instead of displaying the value error message. If I enter an invalid respone for number of tickets such as 10000 the code will just loop back and ask for the user name again instead of indicating that the value entered is invalid. Can you show me where I am missing something?

TICKET_PRICE = 10

tickets_remaining = 100

while tickets_remaining >= 1: print("There are {} tickets remaining".format(tickets_remaining)) user_name = input("What is your first name? ") number_of_tickets = input("Hello {}, how many tickets would you like? ".format (user_name)) try: number_of_tickets = int(number_of_tickets) if number_of_tickets > tickets_remaining: raise ValueError ("There are only {} tickets remaining".format (tickets_remaining))

except ValueError as err: print ("oh no that's no a valid value {}. Please try again".format(err))

else: amount_due = TICKET_PRICE * number_of_tickets print ("The total amount due is ${} ".format (amount_due)) should_proceed = input("Do you want to proceed? Y/N ") if should_proceed.lower() == "y": print ("SOLD") #TODO: gather credit card info and process payment
tickets_remaining -= number_of_tickets else: print ("Thank you {}!".format (user_name)) print ("Sorry there are no more tickets available")

1 Answer

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 49,963 Points

It's hard to tell with how your code is formatted. You should use markdown. I didn't change anything other than possibly indentation and the following appears to work:

TICKET_PRICE = 10

tickets_remaining = 100

while tickets_remaining >= 1:
  print("There are {} tickets remaining".format(tickets_remaining))
  user_name = input("What is your first name? ")
  number_of_tickets = input("Hello {}, how many tickets would you like? ".format(user_name))
  try:
    number_of_tickets = int(number_of_tickets)
    if number_of_tickets > tickets_remaining:
      raise ValueError ("There are only {} tickets remaining".format(tickets_remaining))
  except ValueError as err:
    print ("oh no that's no a valid value {}. Please try again".format(err))

  else:
    amount_due = TICKET_PRICE * number_of_tickets
    print ("The total amount due is ${} ".format (amount_due))
    should_proceed = input("Do you want to proceed? Y/N ")
    if should_proceed.lower() == "y":
      print ("SOLD") #TODO: gather credit card info and process payment
      tickets_remaining -= number_of_tickets
    else:
      print ("Thank you {}!".format (user_name))
print ("Sorry there are no more tickets available")
Deonte Meriwether
Deonte Meriwether
1,513 Points

hmm you know I tried it again and it worked for me also. I think I might have had an extra space in my while statement?? Anyway thank you KRIS for your help! I really appreciate it!