【问题标题】:A python program that's supposed to get 2 variables each iteration, separated by space, a str and an int, and end when the first one is '#'一个 python 程序,每次迭代应该得到 2 个变量,用空格分隔,一个 str 和一个 int,并在第一个是 '#' 时结束
【发布时间】:2021-06-19 01:55:29
【问题描述】:

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

【问题讨论】:

  • 因为它需要 2 个字符。有2个变量x,y
  • 所以在尝试拆分之前检查'#'
  • 注意.. 如果您测试了 y >= 90,那么您不需要测试 y

标签: python loops input space


【解决方案1】:

最好在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 != '#' 是多余的。

【讨论】:

    猜你喜欢
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 2023-03-12
    相关资源
    最近更新 更多