显示列表中的用户选择
Display user choice from list
嗨,我正在写一个程序,目前我对 python、
还很陌生
我想要的是让用户 select 从两个选项中选择
1. Easy Mode
2. Hard Mode
使用字典将用户输入的字符串与您稍后要显示给他们的字符串相关联:
difficulty = {
"1": "Easy Mode",
"2": "Hard Mode",
}
for c, desc in difficulty.items():
print(f"{c}. {desc}")
choice = input("Select your difficulty: ")
while choice not in difficulty:
choice = input(f"Choose one of: {', '.join(difficulty)}: ")
print(f"Role: {difficulty[choice]}")
1. Easy Mode
2. Hard Mode
Select your difficulty: asdf
Choose one of: 1, 2: 2
Role: Hard Mode
你设置了Choice = int(...)
,所以Choice
仍然是1
或2
,所以当你打印它时它会显示为1
或2
。相反,您可以根据输入的 if
语句设置变量 mode
:
Choice = int(input("Select your difficulty: "))
mode = "Invalid choice" # Set a default value
if (Choice == 1):
mode = "Easy Mode"
elif (Choice == 2):
mode = "Hard Mode"
print ("Role: " , mode)
当然,这不考虑用户输入不是这些选择之一的情况,但这是另一个问题:Asking the user for input until they give a valid response
嗨,我正在写一个程序,目前我对 python、
还很陌生我想要的是让用户 select 从两个选项中选择
1. Easy Mode
2. Hard Mode
使用字典将用户输入的字符串与您稍后要显示给他们的字符串相关联:
difficulty = {
"1": "Easy Mode",
"2": "Hard Mode",
}
for c, desc in difficulty.items():
print(f"{c}. {desc}")
choice = input("Select your difficulty: ")
while choice not in difficulty:
choice = input(f"Choose one of: {', '.join(difficulty)}: ")
print(f"Role: {difficulty[choice]}")
1. Easy Mode
2. Hard Mode
Select your difficulty: asdf
Choose one of: 1, 2: 2
Role: Hard Mode
你设置了Choice = int(...)
,所以Choice
仍然是1
或2
,所以当你打印它时它会显示为1
或2
。相反,您可以根据输入的 if
语句设置变量 mode
:
Choice = int(input("Select your difficulty: "))
mode = "Invalid choice" # Set a default value
if (Choice == 1):
mode = "Easy Mode"
elif (Choice == 2):
mode = "Hard Mode"
print ("Role: " , mode)
当然,这不考虑用户输入不是这些选择之一的情况,但这是另一个问题:Asking the user for input until they give a valid response