您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

了解python中的执行流程

了解python中的执行流程

:当您在python中调用自定义函数时,它必须知道它在文件中的位置。我们def function_name():用来定义在脚本中使用的函数的位置。我们必须在调用def function_name():之前先调用function_name(),否则脚本将不知道function_name()并且将引发异常(函数未找到错误)。

通过运行def function_name():它,只会让脚本知道有一个调用函数function_name()但实际上在function_name()调用它之前不会在其中运行代码

在第二个示例中,您是python()在脚本到达之前调用def python(),因此尚不知道是什么python()

的 的顺序是:

1.    def hello(): # Python Now kNows about function hello()
5.        print("hello world")
6.        python()

2.    def python(): # Python Now kNows about function python()
7.        print("testing main")

3.    if __name__ == "__main__":
4.       hello()

该 的顺序是:

1.    python()    # Error because Python doesn't kNow what function python() is yet

-     def python(): # Python doesn't reach this line because of the above error
-         print("testing main")

该 的解决办法是:

1.     def python(): # Python Now kNows about function python()
3.         print("testing main")

2.     python()

从脚本角度 重申 :

def hello(): 
def python(): 
if __name__ == "__main__":
hello() 
print("hello world")
python()
print("testing main")

这是脚本将看到并运行每一行代码的顺序。显然,该脚本知道python()def是在第2python()调用的,在第6行是调用的。

看来您不了解定义范围的含义。阅读有关它。函数的作用域在定义期间不会执行,仅在调用函数时才执行。

python 2022/1/1 18:52:22 有345人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶