【问题标题】:Your code displayed no output您的代码没有显示输出
【发布时间】:2017-09-07 17:52:17
【问题描述】:
我试图运行这段代码:
def readable_timedelta(days):
days = 20
"""Print the number of weeks and days in a number of days."""
#to get the number of weeks we use integer division
weeks = days // 7
#to get the number of days that remain we use %, the modulus operator
remainder = days % 7
return "{ } week(s) and { } day(s)". format(weeks, remainder)
print (readable_timedelta)
我不断得到这个:
您的代码没有显示输出
有人可以帮忙吗?
【问题讨论】:
标签:
python
function
output
【解决方案1】:
你需要实际调用你的函数,例如
readable_timedelta(20)
否则你所做的只是定义一个函数,正如注释所说,这个程序没有输出。
旁注:在return 语句之后放置print 语句(或与此相关的任何内容)是没有意义的,因为不会执行进一步的代码并且函数将执行返回给调用者。
【解决方案2】:
您只需要考虑几件小事。
1.你需要调用你的函数,因为你要打印返回值,你需要在print里面调用。 print(readable_timedelta(20))
2.函数内部不需要变量days = 20。如果您每次都这样做,您的函数将给出相同的结果,即“2 周和 6 天”。
3.每当程序到达return 语句之后,任何代码都不会被执行,因此print() 将永远不会被执行。使用return 或print()。
#Code with return
def readable_timedelta(days):
"""Print the number of weeks and days in a number of days."""
#to get the number of weeks we use integer division
weeks = days // 7
#to get the number of days that remain we use %, the modulus operator
remainder = days % 7
return "{ } week(s) and { } day(s)". format(weeks, remainder)
#Calling Function
print(readable_timedelta(20))
print(readable_timedelta(40))
如果我们在函数定义中使用 print,我们可以简单地调用带有所需参数的函数。
#Code without return
def readable_timedelta(days):
"""Print the number of weeks and days in a number of days."""
#to get the number of weeks we use integer division
weeks = days // 7
#to get the number of days that remain we use %, the modulus operator
remainder = days % 7
print("{ } week(s) and { } day(s)". format(weeks, remainder))
#Calling Function
readable_timedelta(20)
readable_timedelta(40)