1

I have an input that takes two values

input1, input2 = input("Enter two types of pizza separate each with a space: ").split()

I notice that if I only enter one value, my program terminates and a ValueError: not enough values to unpack (expected 2, got 1) is raised. Am I able to raise my own custom ValueError in this case and instead of terminating my program can I make it so it simply reprompts the user to enter it again? I think I can do this with a while loop?

Here is my shot at it.

try: 
    input1, input2 = input("Enter two types of pizza separate each with a space: ").split()
    if input1 = None or input2 = None:
        raise ValueError("You must enter two types separate each with a comma")
except ValueError as err:
    print("Ensure that you enter two types separate each with a comma")
AnthonyM
  • 33
  • 1
  • 8

2 Answers2

0

When you use the multiple assignment syntax a, b = <some list or tuple>, this will immediately throw a ValueError if the number of variable names on the left side does not match the length of the iterable.

A cleaner way is to do this:

values = input("Enter two types of pizza separate each with a space: ").split()
if len(values) == 2:
    input1, input2 = values
    ...
else:
    print("You must enter two types separated by a space!")

If you want to repeatedly prompt until a valid input is entered, you can show the prompt inside a while loop:

message = "Enter two types of pizza separated by a space: "
values = input(message).split()

# Block until exactly two words are entered
while len(values) != 2:
    print("You must enter two types of pizza separated by a space!")
    values = input(message).split()

# After while loop completes, we can safely unpack the values
input1, input2 = values
...
Andrew Eckart
  • 1,618
  • 9
  • 15
0

Using a while loop will certainly do the trick:

input1, input2 = None, None
while input1 is None and input2 is None:
    try: 
        input1, input2 = input("Enter two types of pizza separate each with a space: ").split()
    except ValueError as err:
        print("Ensure that you enter two types separate each with a comma")

Note: As a previous user posted, there is no need to raise your own error as one will automatically be raised when the input is incorrect.

Additionally, don't forget to use == and not just = in conditional statements. :-)

mbcalli
  • 51
  • 5