I usually meet the same issue on my path to learn python. I would like to keep the variable and access to them outside the for loop, can you you give me solution, thanks ?
Here is the code :
n = int(input())
for i in range(n):
operation, arg_1, arg_2 = input().split()
CodePudding user response:
I'm doing problem solving, maybe i see the problem in the wrong angle. When i see this type of code, to solve the problem, i used to wanna get the variables out of the loop to work with them instead to work into the original for loop.
CodePudding user response:
You can't get the variables out if they are created inside the loop (They are temporary local variables easily explained).
If you want to access the values outside the loop you must create variables outside the loop and set the value to them inside the loop.
var1 = 0
for i in range(10):
var1 = 1
var2 = i
print(var2)
print(var1)
In this case i can print var1 outside the loop because it's created before the loop but the value is set inside so it will print 10
.
The var2 is created inside the loop and only lives inside since it's a local variable inside the loop so we can't print this value outside of the loop, but we can print it inside the loop and it will print each iteration of i:
0
1
2
3
4
5
6
7
8
9