San*_*ali -3 python input options
我正在用 Python 开发一个新项目,它的作用是从用户那里获取 3 个输入,然后最后将所有输入显示为 1 个句子。我面临的问题是我想将一些选项作为输入。我已经将所有选项作为普通文本打印为选项 1、2、3、4。那么,如果输入是 1,2,3,4,有什么方法可以改变输入吗?任何有关在 Python 中使用选项作为输入的帮助将不胜感激
小智 5
您可以使用 IF 语句:
print("1: foo")
print("2: bar")
print("3: spam")
print("4: eggs")
inp = int(input("Enter a number: "))
if inp == 1:
inp = "foo"
elif inp == 2:
inp = "bar"
elif inp == 3:
inp = "spam"
elif inp == 4:
inp = "eggs"
else:
print("Invalid input!")
Run Code Online (Sandbox Code Playgroud)
但是,如果有很多选项,您可以(并且可能应该)使用列表:
options = ["foo", "bar", "spam", "eggs"]
# Print out your options
for i in range(len(options)):
print(str(i+1) + ":", options[i])
# Take user input and get the corresponding item from the list
inp = int(input("Enter a number: "))
if inp in range(1, 5):
inp = options[inp-1]
else:
print("Invalid input!")
Run Code Online (Sandbox Code Playgroud)
两个代码完全相同,因此请使用您喜欢的代码。
| 归档时间: |
|
| 查看次数: |
12845 次 |
| 最近记录: |