Search code examples
pythonfor-loopexceptioninputtry-except

How to perform exception handling on this for loop


I would like to perform exception handling on the for statement at the bottom to perform similar exception handling as the function at the top. How would I go about implementing exception handling the for statement at the bottom? I would appreciate examples as I'm trying to learn to program. Regards:

def tested_values(user_input):
  while True:
    try: 
      user_input_int = int(input(user_input))
      return user_input_int
    except ValueError:
      print("Please enter a number!")





def input_values(prompt="Please enter the number of stands you wish to enter the sales values for: "):
  values = tested_values(prompt)
 # user_input = int(input(prompt))

  sales = []

  for sales_values in range(1, values+1):
    prompt =  "Please enter the sales value for " + str(sales_values) + ": "
    sales.append(int(input(prompt)))
  print(sales) 






input_values()

Solution

  • Similarly to how you did it above:

    for sales_values in range(1, values+1):
        while True:
            try:
                prompt =  "Please enter the sales value for " + str(sales_values) + ": "
                sales.append(int(input(prompt)))
                break
            except ValueError:
                print("Please enter a number!")