我的Python代码遇到问题。我应该编写一个程序的问题在于以下和我的代码。当我使用不同的步骤输入值运行它时,我的代码在Wing IDE中工作正常,但是当我将它提交给检查我的代码的系统时,我得到错误,如下所示。在此先感谢您的帮助。我的代码如下。
def activity_level_from_steps(steps):
"""Takes an amount of steps and returns the level of exercise it equals"""
steps = int(steps)
if steps < 1:
level = 'alive?'
elif steps >= 1 and steps < 5000:
level = 'sedentary'
elif steps >= 5000 and steps < 7500:
level = 'very low'
elif steps >= 7500 and steps < 10000:
level = 'low'
elif steps >= 10000 and steps < 12500:
level = 'active'
else:
level = 'very active'
return level
我需要解决的问题
检查我的代码的系统给我的错误
答案 0 :(得分:0)
首先,你需要正确地缩进你的函数体,因为缩进在Python中很重要(tm)。
其次,您已将return
语句缩进到与else
相同的级别。这意味着只有在执行else
子句时才会调用返回。由于默认情况下不返回任何内容的函数会返回None
,因此对于所有其他情况,您的函数将显示为返回None
。
def activity_level_from_steps(steps):
"""Takes an amount of steps and returns the level of exercise it equals"""
steps = int(steps)
if steps < 1:
level = 'alive?'
elif steps >= 1 and steps < 5000:
level = 'sedentary'
elif steps >= 5000 and steps < 7500:
level = 'very low'
elif steps >= 7500 and steps < 10000:
level = 'low'
elif steps >= 10000 and steps < 12500:
level = 'active'
else:
level = 'very active'
return level
这也可以简化,因为每个elif只需要检查活动楼梯的下一步:
if steps < 1:
level = 'alive?'
elif steps < 5000:
level = 'sedentary'
elif steps < 7500:
level = 'very low'
elif steps < 10000:
level = 'low'
elif steps < 12500:
level = 'active'
else:
level = 'very active'
答案 1 :(得分:0)
MatsLindh对你有所了解,但作为关于风格和可读性的一般评论,无论是为了更干,还是为了分离设置和逻辑,你都可以考虑这样的模式:
step_levels = [
(1, 'alive?'),
(5000, 'sedentary'),
(7500, 'very low'),
(10000, 'low'),
(12500, 'active'),
(None, 'very active'),
]
def activity_level_from_steps(steps):
steps = int(steps)
for step, level in step_levels:
if steps < step:
break
return level