使用逻辑运算符简化嵌套条件:逻辑运算符不起作用?

Simplifying Nested Conditionals using Logical Operators: Logical Operators are not working?

我是编码新手,我的 CS 课程才进入第三周。我正在做一个作业,我们必须创建一个嵌套条件,然后使用逻辑运算符将其简化为一个条件。我相信我做对了,但我的简化条件只会选择第一个选项,即使输出小于给定的数量。

嵌套条件:

def steps(s):
   return .04*s
#the average amount of calories burned per step is .04 
walk = steps(6000)
#The variable walk is used to show that my walk was 6,000 steps
hike = steps(7000)
tdee = 1300
#tdee is your Total Daily Energy Expenditure.
day = (tdee + walk + hike)
#this if else statemnet is going to decide of you have burned the recomended number of calories 
for the entire day
if day > 2000:
   print("Success!")
else:
   if day > 1700:
       print("Almost!")
   else:
       if day > 1500:
           print("Try again.")
       else:
           print("Failure.")

简化的单一条件:

def steps(s):
   return .04*s
#the average amount of calories burned per step is .04
walk = steps(500)
#The variable walk is used to show that my walk was 6,000 steps
hike = steps(7000)
tdee = 1300
#tdee is your Total Daily Energy Expenditure.
day = (tdee + walk)
#this if else statement is going to decide if you have burned the recommended number of calories 
for the entire day
if day >= 2000 or >= 1700:
    print("You are within the recommended calorie range.")
else:
    print("You are under the recommended calorie range. Try again.")

根据给定的值,它应该会给出您是 'under' 推荐量的响应,但事实并非如此。 (注意我在任何地方都使用 python 可能也很重要。)

首先,我假设将它带到 Whosebug 只是一个 copy/paste 问题,但如果不是,那么您需要在 for the entire day 行中添加一个 #

尽管如此,对于您的问题,了解几件事很重要。首先,您的 if day >= 2000 or >= 1700 有两个问题:首先,它需要 if day >= 2000 or day >= 1700 才不会崩溃。 Python 的逻辑 andor 等连接两个语句,而 >= 1700 本身不是语句 - 它需要左侧。您可以将链接的条件想象成好像它们被括在括号中一样,例如 if (day >= 2000) or (>= 1700),这更清楚地显示了为什么您需要在 or 之后重复 day。这里的第二件重要的事情是该声明是多余的:如果 day >= 2000 为真,那么 day >= 1700 也会为真。考虑到这一点,您可以将其简化为 if day >= 1700: 并得到等效的语句。

你的问题还有另一个陷阱:你说它不会触发“足够的卡路里”情况,即使它应该触发,但你的基于 walkday 值仅为 1320,这不足以触发它。就此而言,您基于hikeday值仅为1580,也低于1700。我不确定0.04*s的值是否正确,或者7000 steps 太低了,但是无论哪种方式,这些东西的组合都不会使 day 触发 >=1700