问题描述
我尝试了下面的代码,但它不起作用,因为输入需要两个值,所以如果我输入“#”,它会显示一个 ValueError
x = '0'
while(x != '#'):
x,y = map(str,input().split())
y = int(y)
if x != '#':
if y >= 90:
print(f"{x} Alta")
if y < 90:
print(f"{x} Internação")
else:
break
解决方法
最好在 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 != '#'
是多余的。