【问题标题】:python2.7 quit within two input in the same line (separated by space)python2.7在同一行的两个输入内退出(以空格分隔)
【发布时间】:2018-02-23 15:59:45
【问题描述】:

我必须在同一行输入两个值,它们之间用空格隔开。 所以输出会是这样的

123 456

输入是 123 和 456

所以我使用代码

a ,b = map(float, raw_input().split())
print ('input is '), a ,(' and '), b

这个作品 但是当用户输入“-1”时我想立即退出脚本 例如,如果用户为 a 输入 -1 的值,程序将停止读取用户的输入,打印 'wrong input'

输入错误

但是当我尝试输入“-1”并按“输入”时

据说

ValueError: 需要超过 1 个值才能解压

这是否意味着我不应该使用 'map(float, raw_input().split())' ?

【问题讨论】:

    标签: python-2.7 input split valueerror


    【解决方案1】:

    如果您只输入一个输入 (-1),在尝试将其存储在 a、b 中时,pytjon 会抛出一个回溯。

    不要存储在 a,b 中,而是将其存储在列表中。

    如果您想使用地图功能,请使用以下内容:

    1. 有效输入的情况:

      >>> a = map(float, raw_input().split())
      123 456
      >>> if a[0] == -1 :
      ...     print 'Wrong Input'
      ... else :
      ...     print 'input is',a[0],' '.join(['and '+str(i) for i in a[1:]])
      ...
      input is 123.0 and 456.0
      
    2. 输入无效的情况-

      >>> a = map(float, raw_input().split())
      -1
      >>> if a[0] == -1 :
      ...     print 'Wrong Input'
      ... else :
      ...     print 'input is',a[0],' '.join(['and '+str(i) for i in a[1:]])
      ...
      Wrong Input
      
    3. 额外的东西(有效)-

      >>> a = map(float, raw_input().split())
      12 34 56 78
      >>> if a[0] == -1 :
      ...     print 'Wrong Input'
      ... else :
      ...     print 'input is',a[0],' '.join(['and '+str(i) for i in a[1:]])
      ...
      input is 12.0 and 34.0 and 56.0 and 78.0
      
    4. 额外的东西(无效)-

      >>> a = map(float, raw_input().split())
      -1 234
      >>> if a[0] == -1 :
      ...     print 'Wrong Input'
      ... else :
      ...     print 'input is',a[0],' '.join(['and '+str(i) for i in a[1:]])
      ...
      Wrong Input
      

    【讨论】:

      【解决方案2】:

      只需将参数放入列表中,然后对其进行处理:

      params = map(float, raw_input().split())
      

      然后您可以检查 params[0] 是否为 -1 或数组的长度是否与预期不同。检查后,您可以分配:

      a,b=params
      

      【讨论】:

        猜你喜欢
        • 2021-07-27
        • 1970-01-01
        • 2021-06-12
        • 1970-01-01
        • 2016-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-17
        相关资源
        最近更新 更多