python 中作为输入的选项

Options as input in python

我正在 Python 开发一个新项目,它的作用是从用户那里获取 3 个输入,最后将所有输入显示为 1 个句子。我面临的问题是我想输入一些选项。我已经将所有选项作为普通文本打印为选项 1、2、3、4。 那么,如果输入是 1、2、3、4,有什么方法可以更改输入吗? 任何有关在 Python 中使用选项作为输入的帮助将不胜感激

您可以使用 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!")

但是如果有很多选项,您可以(并且可能应该)使用列表:

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!")

两种代码的作用完全相同,因此请使用您喜欢的一种。