最好在input 调用中加入提示。
写入 2 个整数值可以正常工作,例如 14 15。
但是如果我只输入一个值,例如14,那么它就会崩溃:
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)
预期的单个值 # 也会发生同样的情况。
那是因为:
>>> "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)
元组解包在this question 的答案中进行了解释,我鼓励您阅读它们。
由于您的赋值,Python 期望在 map 函数的可迭代结果中找到两个值,所以当它只找到一个时,它会失败。
如果用户输入为空(或只是空格,由于split),也会发生同样的情况。
如果用户输入的值超过 2 个(例如 14 15 16),也会发生同样的情况。
您的代码没有正确处理它。
pythonic 的方法是:
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
我找不到一种 Pythonic 方式来添加对 # 的处理。
但我个人不喜欢过多使用try/except:
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
如果您想强制用户输入正确的值,您可以将其包装在 while 循环中,和/或将其提取到函数中。
另外,因为如果 x == '#' 打破了你的 while 循环,那么你的 while 条件 x != '#' 是多余的。