How to print statement after return in function?(如何在函数中返回后打印语句?)
问题描述
这是我目前拥有的代码:
Here is the code as I currently have it:
def F(n):
t=time.time()
if n==0:
return (0)
elif n==1:
return (1)
else:
return (F(n-1)+F(n-2))
t1==time.time()
return t
F_time==t1-t
print ('It took',F_time,'seconds to sort',n,'values using recursion')
我正在尝试打印n个斐波那契数列并取前后的时间,但是由于return语句,它不会接受return之后的变量,也不接受下面的print语句.
I'm trying to print n numbers of the Fibonacci sequence and take the time before and after, but because of the return statements, it won't accept the variable after the return, nor the following print statement.
推荐答案
为了真正执行函数内部 return
语句之后的事情,请使用 try-finally
像这样:
In order to really execute things after the return
statement(s) inside a function use try-finally
like this:
# platform independent high-resolution clock
from timeit import default_timer as timer
def F(n):
t = timer()
try:
if n == 0:
return 0
elif n == 1:
return 1
else:
return (F(n - 1) + F(n - 2))
finally:
t1 = timer()
F_time = t1 - t
print(u"F(%s) took %.2fµs seconds" % (n, F_time * 1e6))
if __name__ == '__main__':
print("RESULT:", F(4))
输出:
F(1) took 0.92µs seconds
F(0) took 0.84µs seconds
F(2) took 429.78µs seconds
F(1) took 0.84µs seconds
F(3) took 520.12µs seconds
F(1) took 0.67µs seconds
F(0) took 0.75µs seconds
F(2) took 90.85µs seconds
F(4) took 700.82µs seconds
RESULT: 3
注意:在这个例子中,n > 1 的时间当然包括在嵌套递归调用中打印到标准输出的时间,然后在那个简单的例子中支配时间.
Note: in that example here the timings for n > 1 of course include time for printing to stdout in nested recursive calls, which then dominate timing in that trivial example.
这篇关于如何在函数中返回后打印语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在函数中返回后打印语句?


基础教程推荐
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01