即使先前的“ if”语句为true,Python程序也会运行“ else”语句

时间:2020-08-18 22:49:33

标签: python

我对计算机编程非常陌生。我开始编写一个非常简单的脚本,当您输入某人的名字时,该脚本会为您提供前往某人房屋的指示:

# 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'将不会运行。

令人惊讶的是,在其他论坛上我找不到类似的东西。我发现的问题/答案与我正在寻找的问题/答案相似,但是在这种情况下,实际上没有任何问题可以解决。我在做什么错了?

3 个答案:

答案 0 :(得分:5)

这是因为程序中的前两个if语句是分开的并且不相关,因此即使第一个if也可以运行第二个True。您应该使用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.")

答案 1 :(得分:3)

您有一个if和一对与其无关的if/else;连续的if并不是天生就相互关联的,并且else仅与前面的if绑定(可能在它们之间有多个elif块)。如果您希望else仅在所有if都失败的情况下运行,则需要通过将第二个if和一个elif绑定到第一个{ {1}}。这将使您互斥行为;一个并且只有一个块将执行:

if

答案 2 :(得分:1)

它会打印到大卫家的路线,但是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.") 仅适用于班农家。要将所有内容合并为一条语句,请使用else

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