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

时间:2021-02-15 20:36:28

标签: python nested conditional-statements logical-operators

我是编码新手,并且只在我的 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.")

根据给定的值,它应该给出您“低于”推荐数量的回应,但事实并非如此。 (同样重要的是要注意我在任何地方都使用 python。)

1 个答案:

答案 0 :(得分:0)

首先,我假设这只是将它带到 StackOverflow 的复制/粘贴问题,但如果不是,那么您需要在 # 行中添加一个 for the entire day

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

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