0

If there's a value error I want this statement to return to the current question without starting over at the first question. Do I need to make 3 separate loops? What is the best way to approach this? Because if I had 100+ inputs, it could get messy!

while True:
    try:
        num_of_ppl = int(input("How many people? "))
        num_of_pizza = int(input("How many pizza's? "))
        num_of_slices_per_pizza = int(input("How many slice's per pizza? "))

    except ValueError:
        print("You must enter a whole number.\n")
        continue
    break
  • 1
    I wonder what your CPU did to you that you want to run an infinite loop. – Baruch Aug 09 '17 at 19:58
  • If you're going to use loops, I would do three separate loops. I would recommend a recursive solution, though. – Brett Beatty Aug 09 '17 at 20:05
  • Put your queries in a container and loop till the container is empty, when a valid response is received remove the query from the container. – wwii Aug 09 '17 at 21:36

2 Answers2

3

Maybe someone who has more experience than me can say why my approach is wrong but I would do something like this:

def take_input(msg):
  try:
    return int(input(msg))
  except:
    return take_input(msg)


pizzas = take_input("how many pizzas?")
num_of_ppl = take_input("How many people?")

Of course, since you can keep on giving a non-valid answer you might exceed recursion depth. Is there any other thing that I am overlooking?

PYA
  • 8,096
  • 3
  • 21
  • 38
0

Well my friend, not having to constantly rewrite code is the point entirely of functions. How about trying something like this:

def get_answer(instring):
    while True:
        try:
            ret = int(input(instring))      

        except ValueError:
            print("You must enter a whole number.\n")
            continue
        break
    return ret

and then you just have to call that method with the instring as those questions. You could even have a list:

qlist = ["How many people? ", "How many pizza's? ","How many slice's per pizza? "]

and then could use a loop like this:

answers = []
for q in qlist:
    answers.append(get_answer(q))
JoshKopen
  • 940
  • 1
  • 8
  • 22
  • Why not change that last bit to a generator? `answers = [get_answer(q) for q in qlist]` – Eric Ed Lohmar Aug 09 '17 at 20:10
  • That's called a list comprehension, not a generator but you could, I just think written out for loops are easier to understand and read especially if someone is not familiar with python. – JoshKopen Aug 09 '17 at 20:22