我对计算机编程非常陌生。我开始写一个非常简单的脚本,当你输入某人的名字时,它会告诉你他家的方向:
# 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
语句是分开的,不相关的,所以第二个if
仍然运行,即使第一个是True
。您应该使用if..elif..else
:它打印了大卫家的方向,但
else
只适用于班农家。若要将所有语句合并为一条语句,请使用elif
:顺便说一下,如果您想包含许多不同形式的大写字母,您可能需要在比较字符串之前对其进行预处理。一个简单的例子:
您有一个
if
和一个与之无关的配对if/else
;顺序的if
彼此并不是天生相关的,一个else
只绑定到前面的一个if
(可能在它们之间有多个elif
块)。如果希望else
仅在所有if
失败时运行,则需要将第二个if
与第一个if
绑定在一起。这将使你的行为相互排斥;一个且仅一个块将执行:相关问题 更多 >
编程相关推荐