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
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')