xxlxxl 发表于 2020-9-13 17:58:40

if else

weather = input("What is the weather? ").lower()

if weather == "sunny":
    print("Time to ride a crocodile!")
if weather == "rainy":
    print("Rainy dance time!")
if weather == "tornado":
    print("Tornado party!")
else:
    print("Watch TV!")
如果我输入sunny,为什么输出的是
Time to ride a crocodile!
Watch TV!


当他判定是sunny以后这个不就结束了吗?

疾风怪盗 发表于 2020-9-13 18:03:11

你没理解if...elif...elif...else的意思

weather = input("What is the weather? ").lower()

if weather == "sunny":
    print("Time to ride a crocodile!")
elif weather == "rainy":
    print("Rainy dance time!")
elif weather == "tornado":
    print("Tornado party!")
else:
    print("Watch TV!")

疾风怪盗 发表于 2020-9-13 18:05:08

你这样写,相当于分成了三个判断
weather = input("What is the weather? ").lower()

if weather == "sunny":
    print("Time to ride a crocodile!")


if weather == "rainy":
    print("Rainy dance time!")
if weather == "tornado":
    print("Tornado party!")
else:
    print("Watch TV!")

sunrise085 发表于 2020-9-13 18:07:16

本帖最后由 sunrise085 于 2020-9-13 18:08 编辑

你写的是多个if,但是你想要的应该是 if …elif…elif…else…
多个if会都进行判断,可能会进入多个分支;但是 if …elif…elif…else…进行判断只进入一个分支
weather = input("What is the weather? ").lower()

if weather == "sunny":
    print("Time to ride a crocodile!")
elif weather == "rainy":
    print("Rainy dance time!")
elif weather == "tornado":
    print("Tornado party!")
else:
    print("Watch TV!")

靳子轩 发表于 2020-9-13 18:28:49

Python自动把else和turnado的if配对了,你没有输入turnado,所以就打印Watch TV了
页: [1]
查看完整版本: if else