首页 > 解决方案 > Python 中的 Input() 函数:如何根据用户输入创建操作?

问题描述

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

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)

提前致谢!

标签: pythonlistinput

解决方案


默认情况下,输入将采用字符串格式。所以当你读入输入时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. 因此,如果要附加 string ,则应将代码更改为oldList.append(str(1)).

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

速记版:

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

推荐阅读