一个python程序,每次迭代应该得到2个变量,用空格,str和int分隔,并在第一个变量为"#"时结束



我尝试了下面的代码,但它不起作用,因为输入需要两个值,所以如果我输入"#",它会显示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)

Tuple开箱在这个问题的答案中有解释,我鼓励你阅读它们。

由于您的赋值,Python希望在map函数的可迭代结果中找到两个值,因此当它只找到一个值时,它将失败。

如果用户输入为空(或者由于split而只是空白(,也会发生同样的情况
如果用户输入的值超过2个(例如14 15 16(,也会发生同样的情况。

您的代码无法正确处理它。

蟒蛇式的方法是:

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

我找不到一种Python方法来添加对#的处理。

但我个人不太喜欢使用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循环中,和/或将其提取到函数中。

另外,因为你打破了while循环,如果x == '#',那么你的while条件x != '#'是多余的。

最新更新