【问题标题】:Why are only single digit integer inputs working and not double digit integers?为什么只有一位整数输入有效,而不是两位整数?
【发布时间】:2019-06-26 21:24:25
【问题描述】:

我正在尝试编写一个要求输入数字然后打印一行的函数。它对单个数字完美无缺,但是一旦我使用两位数字,我的 if/elif 语句只能看到第一个数字,而不是两个数字一起。

我在 python3 中创建了一个示例函数并运行了一个测试。我尝试将 str 更改为 int 也只是 input() 并没有任何效果。

>>> def test():
...     out = str(input('Choice: '))
...     if out[0] == '1':
...             print('Test1 Worked')
...     elif out[0] == '2':
...             print('Test2 Worked')
...     elif out[0] == '10':
...             print('Test10 Worked')
... 
>>> test()
Choice: 1
Test1 Worked
>>> test()
Choice: 2
Test2 Worked
>>> test()
Choice: 10
Test1 Worked

在最后一次运行 test() 时,我的选择是 10,我希望输出是 Test 10 Worked,但它显示 Test1 Worked。

【问题讨论】:

    标签: python-3.x input integer


    【解决方案1】:

    因为out 是一个字符串,而您正在获取第一个元素out[0],它只是第一个字符。因此out[0] == '10'[0] == '1'

    您必须使用out[:2] == '10',或者,因为很容易搞砸,最好使用if out.startswith('10')。如果你知道整个字符串只是一个数字,那么out == '10' 是安全的。

    【讨论】:

    • 太棒了。谢谢。
    【解决方案2】:

    您可能想要检查 out 的值而不是 out[0],因为 out[0] 将检查您输入的第一个字符

    def test():
      out = str(input('Choice: '))
      if out == '1':
        print('Test1 Worked')
      elif out == '2':
        print('Test2 Worked')
      elif out == '10':
       print('Test10 Worked')
    

    【讨论】:

    • 同意.. 我删除了所有 [0] 条目,我现在就像雨一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    相关资源
    最近更新 更多