布尔变量和If语句对true语句失败 [英] Boolean Variables and If statement fails for true statements
问题描述
提示:
Clunker Motors Inc.正在召回其1999年– 2002年的 Extravagant 系列中的所有车辆.在给定变量
modelYear
和modelName
的情况下,如果modelYear
和modelName
的值与召回详细信息匹配并分配否
否则.
Clunker Motors Inc. is recalling all vehicles in its Extravagant line from model years 1999 – 2002. Given variables
modelYear
andmodelName
write a statement that assignsTrue
torecalled
if the values ofmodelYear
andmodelName
match the recall details and assignsFalse
otherwise.
我编写了这段代码,但是对于正确的语句却一直得到错误的答案.虚假陈述来得很好.
I wrote this code but kept getting wrong answers for the true statements. The false statements came through just fine.
modelYear >= 1999 and modelYear <= 2002
modelName == "Extravagant"
if modelYear == True and modelName == True:
recalled = True
else:
recalled = False
推荐答案
执行时-
modelYear >= 1999 and modelYear <= 2002
modelName == "Extravagant"
您只是舍弃了这些布尔表达式的结果,这并不能神奇地产生 modelYear
或 modelName
布尔值.
You are just throwing away the result of those boolean expressions, this does not magically make modelYear
or modelName
boolean values.
您可以简单地在 if
块本身中使用表达式,而不是尝试创建布尔值.示例-
Instead of trying to create boolean values, you can simply use the expression in the if
block itself. Example -
if 1999 <= modelYear <= 2002 and modelName == "Extravagant":
recalled = True
else:
recalled = False
如果在真实代码的 if
块中,您要做的就是分配布尔值,那么您可以--p
And if inside the if
block in your real code, all you do is assign the boolean value, then you can do -
recalled = 1999 <= modelYear <= 2002 and modelName == "Extravagant"
这篇关于布尔变量和If语句对true语句失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!