首页 > 解决方案 > 在缩进之外使用变量

问题描述

压痕图片

嗨,我的朋友们,我想问一个问题。我在第一个缩进中分配了一个变量名 num,然后在第三个缩进中使用它,并且它起作用了。它的逻辑是什么?据我所知,您只能在缩进内使用变量。是否可以在其他缩进中使用它?

标签: indentation

解决方案


在 Python 中,变量是在块中声明的。块是模块、函数体和类定义。如果您在块内声明某些内容,则不得在该块外使用它。块可以包含其他块。

例子:

bar = 0 # if you declare a variable within a module, but outside of a function

def foo(): # you can use the variable anywhere within the module.
    print(bar) # even in functions. Since it is within the block of the module


def x():    # If you define a function x
    y = 0   # and the vars y and z within function x
    z = 45  
    if y == 0: # you may use y and z anywhere within x
        print(z)

print(y)    # but you cannot use y or z outside of the function.
            # Since it is outside of the block of the function

推荐阅读