python - 为什么我得到错误的输出?
问题描述
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.00
burrito 的价格5.0
。那么,我是怎么得到的5.5
?
解决方案
你应该更换
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
推荐阅读
- python-3.x - BeautifulSoup .get_text() 元素不返回任何结果
- c++ - 从 dll 调用任何函数都会引发错误
- python - 如何使用 Tensorflow 操作加速 python 的 while 循环?
- mysql - MYSQL 加入并显示不匹配的记录
- arduino - 使用 Arduino / ESP8266 / ESP32 控制交流电
- reactjs - 为什么 useEffect 第一次运行,即使它正在收听道具?
- numpy - pytorch 张量步幅 - 它是如何工作的
- node.js - 如何为打字稿安装 discord.js 的类型?
- xcode - 在选项卡或单独窗口中打开第二个窗口
- python - 多次重复numpy数组