Brendan Brendan - 1 year ago 81
Python Question

How to allow a single input in a "two-input input"?

So, I have this code that allows two inputs:

a, b = input("Enter a command: ").split()
if(a == 'hello'):
elif(a == 'color' and b == '3'):
print("Changing color to 3")
#example, doesn't actually change color
elif(a == 'color' and b == '2'):
print("Changing color to 2")
print("invalid command")

And the "color 2"/"color 3" thing works. However, typing "hello", as it's
a single word, gives me this error:

ValueError: not enough values to unpack (expected 2, got 1)

So, how can I get around/fix this?
I hope this was formatted correctly and everything, thanks for taking the time to look at the question. I'm pretty new to python, so sorry if it's a simple fix.

wim wim
Answer Source

If you don't know in advance how many arguments there are to the command, then you can not use this construct:

a, b = input("Enter a command: ").split()

You could try like this instead:

a, _, b = input("Enter a command: ").partition(' ')

Or, may I suggest to use more verbose variable names:

command, separator, arguments = input("Enter a command: ").partition(' ')

It will work for any number of arguments after the first 'command' word, because str.partition is guaranteed to return a 3-tuple.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download