Home > other >  The goddess of festival happiness! Consult a local variable scope for loop in Python
The goddess of festival happiness! Consult a local variable scope for loop in Python

Time:09-26

 
# demo for loop the basic use of

Foods=[ps "pizza", "NRM beef noodles", "SGMX sand pot rice noodle", "hg hot pot", "kr barbecue"]

For the food in foods: # for loop statements, be careful not to lose the colon
Print (food) # loop statements, pay attention to the indentation.

Print (" \ r \ n "+ food +" \ r \ n ") # variable food out of the loop can also use? Not a local variable? Scope?
Foods. Sort (reverse=True)

# for the food in foods: the food here the variable is defined on a cycle? Or the new definition in this cycle?
Print (" my favorite foods are: "+ food. Title ())
Print (" looking forward to the next to be able to eat my favorite "+ food. The upper ())
Print (" \ r \ n all of these are my favourite food. ")
Print (" and my favorite food is: "+ food) # food variable scope mechanism seems to be different from the mechanism of Java?

Java transfer Python beginners, the code is like this.
My confusion is:
1. The Python for loop variables defined within the food, why does it still can use at the end of the cycle? Python code block internal variables, what is the mechanism of the scope of its scope?
2. The food of the variables in the code of the second loop is before the first loop has been created, or in the second loop of the newly created?
3. The code from the first cycle to the second loop, the food what is the state variable changes in memory? How its address pointer is pointing to the entity?
In fact, these three questions, basically is a big problem, is about Python, the mechanism of the local variable with the Java seems to have very big different. Great god help me to solve my confusion. Thanks! Thank you very much!

PS: ladies and gentlemen, dear girls, mothers and sisters grace goddess ~ wish you joy festival ~

CodePudding user response:

In code, now that I met in python, you of the last cycle of food as long as not being redefined, then his value will not change
The food in front of the food will be behind the cover
I hope it can help you, you can test a few times more

CodePudding user response:

1, two loops foot is not the same, you can change the English
2, should think so, the second with the foot is to redefine a variable memory address is different

CodePudding user response:

Python for sequential execution, as long as is not clear, the variable will be in the address,
Can use the id (variable) to check the address, you can print (id) (food) to see if the address changes, you know, change and status quo when changed
  • Related