python - 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)
提前致谢!
解决方案
默认情况下,输入将采用字符串格式。所以当你读入输入时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)
推荐阅读
- laravel - 419 Page Expired while login or register on laravel 7
- video-streaming - Media Foundation H264 硬件编码器中的锯齿/质量问题,尤其是文本(文本上的锯齿和模糊)
- flutter - 如何使用 Dio 在 Flutter 中上传多个图像/文件?
- python - 记录python中类之间的常用方法
- javascript - 悬停时在 Font-Awesome 图标之间切换
- ignite - 无法通过 java 代码启动 ignite 服务器
- vue.js - Vuetify v-Date-Picker 没有在日期选择器日历中显示正确的日期
- ruby - 如何使用 RVM 在旧 Ruby 版本中启用制表符补全?
- javascript - 使用 chai 期望所有数组元素匹配单个值而不管大小
- hibernate - 出现错误“您无法在托管事务期间提交”|“您无法在从属会话期间回滚”