首页 > 解决方案 > 为什么我得到错误的输出?

问题描述

item = "burrito"
meat = "chicken"
queso = False
guacamole = False
double_meat = False
if item == "quesadilla":
    base_price = 4.0
elif item == "burrito":
    base_price = 5.0
else:
    base_price = 4.5


if meat == "steak" or "pork":
    if double_meat:  
        if guacamole and queso and not item == "nachos":
            base_price += 1.00 + 1.50 + 0.50 + 1.00
        elif guacamole:
            base_price += 0.50 + 1.50 + 1.00
        else:
            base_price += 0.50 + 1.50 
    else:
        if guacamole and queso and not item == "nachos":
            base_price += 1.00 + 0.50 + 1.00
        elif guacamole:
            base_price += 0.50 + 1.00
        else:
            base_price += 0.50  
else:
    if double_meat:  
        if guacamole and queso and not item == "nachos":
            base_price += 1.00 + 1.00 + 1.00
        elif guacamole:
            base_price += 1.00 + 1.00
        else:
            base_price += 1.00 
    else:
        if guacamole and queso and not item == "nachos":
            base_price += 1.00 + 1.00
        elif guacamole:
            base_price += 1.00
        else:
            base_price += 0.00
print(base_price)

代码应计算给定条件下的膳食成本(第 1 到 5 行)。这些条件可以改变。上面代码的输出应该是5.0,但我得到的输出等于5.5. 场景是else代码的最后一条语句 wherebase_price应该是 5+0.00 = 5.00burrito 的价格5.0。那么,我是怎么得到的5.5

标签: python

解决方案


你应该更换

if meat == "steak" or "pork":

if meat == "steak" or meat == "pork":

解释:

meat == "steak" or "pork"将按顺序执行(==优先级高于or),因此meat=="steak"为 False,表达式为False or "Pork"which is "pork"which is True。

>>> meat = 'chicken'
>>> meat == 'steak' or 'pork'
'pork'
>>> meat == 'steak' or meat == 'pork'
False

推荐阅读