【问题标题】:Input() function in Python: How can I create an action out of user input?Python 中的 Input() 函数:如何根据用户输入创建操作?
【发布时间】:2020-06-12 19:03:59
【问题描述】:

我想知道如何从用户输入中获取与列表相关的操作。这将是我的“解决方案”,但它不起作用,只是将用户的输入返回给我。

oldList = ['1', '2']
newList = input('Which number should be included in the List?')
if newList == 1:
    oldList.append(1)
elif newList == 2:
    oldList.append(2)

print(oldList)

提前致谢!

【问题讨论】:

标签: python list input


【解决方案1】:

默认情况下输入将是字符串格式。因此,当您读取newList 中的输入时,其值为:'1'。所以下面的代码可以工作。

oldList = ['1', '2']
newList = input('Which number should be included in the List?') 
if newList == '1':     # and not 1
    oldList.append(1)
elif newList == '2':
    oldList.append(2)

print(oldList)

输入: 1

输出:

Which number should be included in the List?
['1', '2', 1]

您也可以尝试保持相同的比较并将newList 转换为int。那也行。


注意:上面的代码会将一个整数附加到oldList。所以,如果你想追加字符串,你应该把代码改成oldList.append(str(1))

还有一件事,如果你只是想附加一个用户输入的数字,你可以使用这个 -

速写版:

oldList = ['1', '2']
oldList.append(int(input('Which number should be included in the List?')))
print(oldList)

【讨论】:

    【解决方案2】:
    oldList = ['1', '2']
    newList = str(input('Which number should be included in the List?'))
    if newList == str(1):
        oldList.append(str(1))
    elif newList == str(2):
        oldList.append(str(2))
    
    print(oldList)
    

    【讨论】:

    • 你能解释一下为什么这里需要str()吗?请记住,Stack Overflow 的目标不仅仅是人们展示正确的答案,而是帮助他们理解它。看看@Abhishek 的回答——这是一个很好的例子,说明了如何解决这些类型的问题。
    【解决方案3】:

    input 函数返回字符串变量,而不是数字,所以不是这个:

    if newList==1:
     oldList.append(1)
    

    使用:

    if newList=='1':
     oldList.append('1')
    

    但是,如果您像这样直接附加输入,您的代码会更简洁:

    oldList.append(input('Which number should be included in the List?'))
    

    -编辑:如果您想确保只存储数字,您也可以使用以下代码:

    try:
     oldList.append(int(input('Which number should be included in the List?'))
    except:
     print("That wasn't a number!")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-29
      • 2015-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 2017-09-11
      相关资源
      最近更新 更多