indentation - 在缩进之外使用变量
问题描述
嗨,我的朋友们,我想问一个问题。我在第一个缩进中分配了一个变量名 num,然后在第三个缩进中使用它,并且它起作用了。它的逻辑是什么?据我所知,您只能在缩进内使用变量。是否可以在其他缩进中使用它?
解决方案
在 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
推荐阅读
- arrays - 在 bash 中删除列表或数组的一些条目
- wordpress - 禁止您没有权限访问此服务器上的 /wp-login.php
- c# - Nunit 3 GUI 运行器
- azure-devops - 在 Azure DevOps 中是否可以编写一个 WIQL 来返回与多个工作项关联的提交?
- css - 如何在我的移动版本上将我的单个 insta-feed 行分成 2 列?
- python - 我定义了一个函数来从 Quora 获取任何特定问题的评论,但它只获取一些评论。我的代码有什么问题?
- java - 为什么我的代码会跳过if语句中的return语句,然后执行else语句体?
- linux-kernel - 在 ACPI 转储中,_Y06 上的基地址 0x0 的 Memory32Fixed() 代表什么?
- python - Google 图片 API 的 execute_transforms() 返回“出现错误”
- c# - c#线程到线程异常,在第二个表单上使用进度条时将数据加载到datagridview