为什么python打印最后一个密钥



我是python的新手,想知道结果。我只是想了解它。 假设我有以下字典:

employee = {   
'user_name': 'my name',   
'password': 'hello',   
'mobile phone': 123456789
}
for i in employee:    
print(i)  
print(i)

结果如下:

user_name
password
​mobile phone​
mobile phone

如果您注意到(手机(已经打印了两次,第二个来自上面代码中的第二次打印。

  1. 为什么会这样? 我希望收到此错误:

名称错误: 未定义名称"i">

像往常一样由Python。

  1. 如果我想访问第一个或第二个密钥怎么办? 我是否可以使用相同的方式访问最后一个密钥(无需写入密钥名称或编号(?

你的问题是范围:

Python 的作用域行为由函数作用域定义:有关更多文档,请参阅此处

由于您遇到了 main 函数,因此ivar 仍将在print语句中定义,因为它在for循环的同一范围内。

因此,它将具有循环最后一次迭代的值(即"移动电话"(

#global scope (main function)
employee = {   
'user_name': 'my name',   
'password': 'hello',   
'mobile phone': 123456789
}
for i in employee:   
#you are still in the global scope here !!
print(i)  
#and here too....so the "i" variable will have the value of your last iteration !
print(i)

更清楚的是,如果你写这样的东西:


#global scope (main function)
employee = {   
'user_name': 'my name',   
'password': 'hello',   
'mobile phone': 123456789
}
def show_employees() :
for i in employee:   
#you are in the "show_employees" function scope here !!
print(i)  
show_employees() # here you call the function
#and here you will get your "expected error" because "i" is not defined in the global scope
print(i)

输出:

文件"main.py",第 18 行,在 打印(I( 名称错误: 未定义名称"i">

Python 中的 Scope 与其他语言(如 C++、C# 或 Java(略有不同。在这些语言中,声明

for (int i=0; i<10; i++) { ... }

i只会在循环范围内定义。Python的情况并非如此。i仍然存在,并具有分配的最后一个值。

如果我想访问第一个或第二个密钥怎么办? 我是否可以访问最后一个密钥(不写入密钥名称或编号(?

不。除非您使循环停止在不同的位置。

最新更新