Python Else语句无效
当用户输入与指定的字母“A”、“A”、“B”、“B”、“C”、“C”、“E”、“E”有任何不同时,它不会运行Python Else语句无效,python,python-3.x,Python,Python 3.x,当用户输入与指定的字母“A”、“A”、“B”、“B”、“C”、“C”、“E”、“E”有任何不同时,它不会运行else语句,而只是关闭。我还想让它再次重复该程序,如果用户输入的不是任何指定的字母,我如何才能做到这一点?我相信这将是我必须在else声明中添加的内容 user\u input=input() 如果用户输入(“A”、“A”、“B”、“B”、“C”、“C”、“E”、“E”): 如果用户输入==“A”或用户输入==“A”: 打印(“您选择了一个”) elif user_input==“B”或
else
语句,而只是关闭。我还想让它再次重复该程序,如果用户输入的不是任何指定的字母,我如何才能做到这一点?我相信这将是我必须在else声明中添加的内容
user\u input=input()
如果用户输入(“A”、“A”、“B”、“B”、“C”、“C”、“E”、“E”):
如果用户输入==“A”或用户输入==“A”:
打印(“您选择了一个”)
elif user_input==“B”或user_input==“B”:
打印(“您选择了B”)
elif user_input==“C”或user_input==“C”:
打印(“您选择了C”)
elif user_input==“E”或user_input==“E”:
打印(“您选择退出程序”)
其他:
打印(“出现问题,请重试”)
您的else
应该是外部if
(同样的缩进)的一部分,因为现在它是内部if
此外,您还可以简化测试,首先使用.upper()
仅处理大写字母,然后在“ABCDE”中使用user\u输入测试是否包含
再问一次版本
Python非常特定于缩进。这应该可以做到:
user_input = input()
if user_input in ("A", "a", "B", "b", "C", "c", "E", "e"):
if user_input == "A" or user_input == "a":
print("You chose A")
elif user_input == "B" or user_input == "b":
print("You chose B")
elif user_input == "C" or user_input == "c":
print("You chose C")
elif user_input == "E" or user_input == "e":
print("You chose to exit the program")
else:
print("Something went wrong, try again")
这是因为最后一个else的缩进-它嵌套在第一个if中。由于缩进,您的答案无法编译,请检查:DYour username更酷。:)谢谢,这就解决了问题!有没有关于在else语句中如何将代码重复到第一行的建议?@verycool只需添加它。如果您满意,您可以接受答案;)
user_input = input("Please choose: ").upper()
while user_input not in "ABCDE":
print("Something went wrong, try again: ")
user_input = input().upper()
if user_input == "A":
print("You chose A")
elif user_input == "B":
print("You chose B")
elif user_input == "C":
print("You chose C")
elif user_input == "E":
print("You chose to exit the program")
user_input = input()
if user_input in ("A", "a", "B", "b", "C", "c", "E", "e"):
if user_input == "A" or user_input == "a":
print("You chose A")
elif user_input == "B" or user_input == "b":
print("You chose B")
elif user_input == "C" or user_input == "c":
print("You chose C")
elif user_input == "E" or user_input == "e":
print("You chose to exit the program")
else:
print("Something went wrong, try again")