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

2024-09-24 22:30:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编码还不熟悉,刚上完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,这一点也很重要。)


Tags: ofthetoifissteps条件else
1条回答
网友
1楼 · 发布于 2024-09-24 22:30:50

首先,我假设这只是一个复制/粘贴问题,会导致StackOverflow,但如果不是,那么您需要在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步是否太低,但不管怎样,这些因素的组合都不会导致day触发>=1700

相关问题 更多 >