Reputation: 51
I am new in python and wondering about the result. I just want to understand it. suppose I have the following dictionary:
employee = {
'user_name': 'my name',
'password': 'hello',
'mobile phone': 123456789
}
for i in employee:
print(i)
print(i)
and here is the result:
user_name
password
mobile phone
mobile phone
if you notice that the (mobile phone) has been printed twice.the second one comes from the second print in the above code.
NameError: name 'i' is not defined
as usual by python.
Upvotes: 1
Views: 63
Reputation: 3932
Your problem here is the scope :
Python's scope behavior is defined by function scope : please see here for more documentation
Since you are running into the main function, the i
var will still be defined in the print
statement , because it is in the same scope of the for
loop.
So it will have the value of the last iteration of your loop (i.e "mobile phone")
#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)
To be more clear, if you would write something like :
#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)
Output :
File "main.py", line 18, in print(i) NameError: name 'i' is not defined
Upvotes: 2
Reputation: 59279
Scope in Python is a bit different than in other languages like C++, C# or Java. In those languages, declaring
for (int i=0; i<10; i++) { ... }
i
would only be defined in the scope of the loop. That's not the case for Python. i
remains existent and has the last value it was assigned.
what if I want to access the first or second key? can I access with the same what I access the last one (without writing the key name or number)?
No. Except you make the loop stop at a different position.
Upvotes: 1