错误的if-else案例在Python中

时间:2015-08-09 06:42:53

标签: python

有人可以看看这个并告诉我出了什么问题吗? 我尝试过运行它,但是当你说no下雨和no下雪时,它仍打印出if true statement You can't ride your bike

raining = input("Is it raining right now?\nYes or No?\n")
if raining.lower() == "yes" :
    raining = True
else:
    raining = False
snowing = input("Is it snowing out?\nYes or No\n")
if snowing.lower() == "yes" :
    snowing = True
else:
    snowing = False
if raining or snowing == True :
    print("You can't ride your bike")
if raining and snowing == False :
    print("You can ride your bike")

cost = input("How much is your new PC?")
cash = input("How much money do you have?")
total = float(cash) + float(cost)
if total < 0 :
    print("You can't buy it")
if total >= 0 :
    print ("You can buy it")

2 个答案:

答案 0 :(得分:2)

if raining and snowing == False被解释为:

if raining == True and snowing == False

您应该按如下方式更新第二个if语句:

if raining == False and snowing == False:
    ...

由于if rainingif raining == True对于检查布尔值是相同的,因此您可以像这样简化逻辑:

if raining or snowing:
    print("You can't ride your bike")
else:
    # implies "not (raining or snowing)" or "(not raining) and (not snowing)"
    print("You can ride your bike")

答案 1 :(得分:1)

只需将and条件更改为else,然后使用or条件中的括号。

raining = input("Is it raining right now?\nYes or No?\n")

if raining.lower() == "yes" :
    raining = True
else:
    raining = False
snowing = input("Is it snowing out?\nYes or No\n")

if snowing.lower() == "yes" :
    snowing = True
else:
    snowing = False
if (raining or snowing) == True :
    print("You can't ride your bike")
else:
    print("You can ride your bike")

cost = input("How much is your new PC?")
cash = input("How much money do you have?")
total = float(cash) + float(cost)
if total < 0 :
    print("You can't buy it")
if total >= 0 :
    print ("You can buy it")