Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why does variable not change in function

im using python 3.10.2
i wanted to make a program that cycled thru red green and blue values but the variable is not changing allthough i made variables global before the for loop

i wrote this


r,g,b=255,0,0
def c(c,v):
    global r,g,b
    for _ in range(255):
        exec(f'{c}-=1')
        exec(f'{v}+=1')
        print(r,g,b)
c('r','g')
c('g','b')
c('b','r')

it prints this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

255 0 0
255 0 0
255 0 0
255 0 0
255 0 0
255 0 0
...

(many more times than this)

i expected it to print this

255 0 0
254 1 0
253 2 0
252 3 0
251 4 0
250 5 0
...

what do i need to do
(sorry for bad english)

>Solution :

It seems that the global keyword declaration is not read by the exec function.

I think I got the wanted result doing this

(Also you could have a much simpler solution without using exec but I guess you have your reasons 🙂 )

r, g, b = 255, 0, 0


def c(c, v):
    for _ in range(255):
        exec(f'global {c} ; {c}-=1')
        exec(f'global {v}; {v}+=1')
        print(r, g, b)


c('r', 'g')
c('g', 'b')
c('b', 'r')

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading