Skip to content
← Back to Community
Updating Variables In For Loop
Profile icon
SamKunefeh

Hello everyone,

In this repl, I try to update my variables by looping through the new values, and then assigning them to the variables. However, instead of changing the variable, they only change the temporary var inside the for loop, but not the actual variable. So, how can I fix this while still using a for loop? (Because I need to use this in a bigger project)

Voters
Profile icon
SamKunefeh
Comments
hotnewtop
Profile icon
SamKunefeh

Sorry guys, what I meant to say was looping through an iterable of the variables(x and y in this case) and then updating the variables by getting the new value from a dictionary. The problem with this however is that it only changes the temporary local variable in the for loop and not the actual x and y values.

Profile icon
Coder100

Two ways

predefining

myStr = "" while True: myStr = "something else" # now it changes the global scope

global

while True: global myStr myStr = "something else" # same thing
Profile icon
SamKunefeh

@Coder100 Oops, view the new updated code because I wasn’t so clear sbout the problem.

Profile icon
RayhanADev

Heya @Jackbaklava

To define a global variable simply type global in front of the variable! That should work, but if not feel free to bug me about it! Cheers.
~ Ray <3

Profile icon
SamKunefeh

@RayhanADev Oops, view the new updated code.

Profile icon
Axrevyn

Declaring it a global variable?
Simply put global in front of the name of the variable inside of the function.

Profile icon
SamKunefeh

@Axrevyn Oops, view the new updated code.