Python 程序运行"else"语句,即使前面的 "if" 语句为真



我对计算机编程非常陌生。我开始写一个非常简单的脚本,当你输入某人的名字时,它会指引你去他们家:

# Users and Directions:
davids_house = "Directions to David's home from X... n East on Y, n South on Z," 
" n West on A, n South on B, n first C on the right."
bannons_house = "bannons directions here"
# Asking the user where he/she would like to go:
destination = input("Where would you like to go? ")
# Reads out a set of directions depending on what name was picked:
if destination in ['Davids_House', 'davids_house', 'Davids_house', 'davids_House']:
print(davids_house)
if destination in ['Bannons_House', 'bannons_house', 'Bannons_house', 'bannons_House']:
print(bannons_house)
else:
print("Sorry, that's not an option.")

每当我运行这个程序并到达它给出指示的点时,我都会给它一个有效的输入,比如"davids_house"。它会打印出指示,但也会运行"else"语句。当我键入一个无效值时,它执行我希望它执行的操作,并且只显示";对不起,这不是一个选项">

我的印象是,除非"if"语句对有效值不满意,否则"else"不会运行。

令人惊讶的是,我在其他论坛上还没有找到这样的东西。我找到了与我想要的类似的问题/答案,但在这个特定的案例中,没有什么能真正解决我的问题。我做错了什么?

这是因为程序中的前两个if语句是分开的,不相关,所以即使第一个是True,第二个if仍然运行。您应该使用if..elif..else:

if destination in ['Davids_House', 'davids_house', 'Davids_house', 'davids_House']:
print(davids_house)
elif destination in ['Bannons_House', 'bannons_house', 'Bannons_house', 'bannons_House']:
print(bannons_house)
else:
print("Sorry, that's not an option.")

您有一个if和一个与其无关的成对if/else;连续的if不天生彼此相关,并且else仅与一个先前的if绑定(可能在它们之间具有多个elif块(。如果希望else仅在所有if都失败时运行,则需要将它们绑定在一起,方法是将第二个if设置为绑定到第一个ifelif。这会让你们产生相互排斥的行为;只有一个区块会执行:

if destination in ['Davids_House', 'davids_house', 'Davids_house', 'davids_House']:
print(davids_house)
# Next line changed to elif from if
elif destination in ['Bannons_House', 'bannons_house', 'Bannons_house', 'bannons_House']:
print(bannons_house)
else:
print("Sorry, that's not an option.")

它打印到David家的方向,但else仅适用于Bannon家。要将所有这些语句合并为一个语句,请使用elif:

if destination in ['Davids_House', 'davids_house', 'Davids_house', 'davids_House']:
print(davids_house)
elif destination in ['Bannons_House', 'bannons_house', 'Bannons_house', 'bannons_House']:
print(bannons_house)
else:
print("Sorry, that's not an option.")

顺便说一句,如果你想包括许多不同形式的大写,你可能需要在比较字符串之前对其进行预处理

if destination.casefold() == 'davids_house':

最新更新