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

2024-09-30 05:16:20 发布

您现在位置: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'不会运行

令人惊讶的是,我在其他论坛上找不到类似的内容。我发现问题/答案与我正在寻找的类似,但在这个具体案例中,没有任何东西能真正解决我的问题。我做错了什么


Tags: thetoifon方向destinationelsehouse
3条回答

这是因为程序中的前两个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.")

它打印了大卫家的方向,但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.")

顺便说一下,如果您想包含许多不同形式的大写字母,您可能需要在比较字符串之前对其进行预处理。一个简单的例子:

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

您有一个if和一个与之无关的配对if/else;顺序的if彼此并不是天生相关的,一个else只绑定到前面的一个if(可能在它们之间有多个elif块)。如果希望else仅在所有if失败时运行,则需要将第二个if与第一个if绑定在一起。这将使你的行为相互排斥;一个且仅一个块将执行:

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

相关问题 更多 >

    热门问题