Better to put a prompt in the input
call.
Writing 2 integer values work fine, for example 14 15
.
But if I put just one value, for example 14
then it crashes :
Traceback (most recent call last):
File "C:/PycharmProjects/stack_overflow/68042991.py", line 3, in <module>
x, y = map(str, input("type 2 integer values : ").split())
ValueError: not enough values to unpack (expected 2, got 1)
The same happens with the expected single value #
.
That's because :
>>> "14 15".split() # what `split` gives us when applied to the user `input`
['14', '15']
>>> list(map(str, ['14', '15'])) # mapping to strings
['14', '15']
>>> x, y = ['14', '15'] # and tuple-unpacking it into the 2 variables
>>> x # gives use the expected result
'14'
>>> y
'15'
>>> "14".split() # but what if the user `input`ed only one value ?
['14'] # it gets splitted into a list of length 1
>>> x, y = ['14'] # which can't be tuple-unpacked
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: not enough values to unpack (expected 2, got 1)
Tuple unpacking is explained in this question's answers, I encourage you to read them.
Because of your assignment, Python expects to find two values in the iterable result of the map
function, so when it finds only one, it fails.
The same happens if the user input is empty (or just whitespaces, due to split
).
The same happens if the user input is more than 2 values (for example 14 15 16
).
Your code does not handle it properly.
The pythonic way to do it is :
the_user_input = input("type 2 integer values : ")
try:
x, y = the_user_input.split()
except ValueError: # unpacking error
... # what to do in case of an error
else:
... # do what's next
I could not find a Pythonic way to add the handling of #
in it.
But I personnaly prefer not to use try/except
too much :
the_splitted_user_input = input("type 2 integer values : ").split()
if len(the_splitted_user_input) == 1 and the_splitted_user_input[0] == "#":
break
if len(the_splitted_user_input) == 2:
x, y = the_splitted_user_input # assured to work
... # do what's next
else:
... # what to do in case of an error
If you want to force the user to type correct values, you can wrap it up in a while
loop, and/or extract it into a function.
Also, because you break out of you while loop if x == '#'
then your while condition x != '#'
is redundant.