无法获取两个if语句和一个else语句来执行

时间:2016-08-11 02:16:29

标签: python if-statement

所以目前我正在尝试制作个人伙伴计划。我希望它是两个if语句和另一个。这两个if语句有不同的单词触发器,所以这就是为什么有两个。当我想创建一个else语句时会出现问题,所以如果某个单词触发器没有输入,它仍会说些什么。这是代码

sport = input("What sports do you play?\n")
if sport in ['soccer','baseball','dance','basketball','golf','skiing','surfing']:
    print(sport, "sounds fun")
if sport in ['none','not at the moment','nope','none atm','natm']:
    print("Im not really into sports either")
else:
    print(sport, "is a sport?")

你可以看到else语句应该回应“Thumbwrestling是一项运动吗?”。相反,如果我说列出的运动会触发“棒球听起来很有趣”,“棒球是一项运动吗?”我不希望它同时触发它们。难道我做错了什么?请帮忙!

2 个答案:

答案 0 :(得分:3)

sport = input("What sports do you play?\n")
if sport in ['soccer','baseball','dance','basketball','golf','skiing','surfing']:
    print(sport, "sounds fun")
elif sport in ['none','not at the moment','nope','none atm','natm']:
    print("Im not really into sports either")
else:
    print(sport, "is a sport?")

请注意elif而不是第二个if。这代表else if,意味着在语句链中,只会执行一个。

答案 1 :(得分:2)

使用if-elif-else语句来区分两种以上的情况,而不是条件语句if-else

if sport in ['soccer','baseball','dance','basketball','golf','skiing','surfing']:
    print(sport, "sounds fun")
elif sport in ['none','not at the moment','nope','none atm','natm']:
    print("I'm not really into sports either")
else:
    print(sport, "is a sport?")

如果您要添加另一个案例,除了我在代码中改进的案例之外,只需坚持if-elif-else语句的语法模式:

if expression1:
   statement(s)
elif expression2:
   statement(s)
elif expression3: #You can add another line of elif if you add another case, here it is labeled expression3.
   statement(s)
else:
   statement(s)