#Global variables help

1 messages · Page 1 of 1 (latest)

wise falcon
#
    global c
    c=a+b
    def f2():
        global c
        c=2+b
    f2()
    print(c)
f1(1,2)```
Is that the way I can manipulate a variable with inner functions?
do i have to write global c in every funcion it is used?
neon idol
#

Why don't you have c as an argument?

#

And return it

wise falcon
#

you mean smth like this?

#

def f1(a,b): c=a+b def f2(c,b): c=c+b return c f2(c,b) return c print(f1(1,2))

neon idol
#

I'm not sure why you are defining a function inside a function but it'd be something like this. I changed the line where you call f2 to store the return value from it back into c

def f1(a,b):
    c=a+b
    def f2(c,b):
        c=c+b
        return c
    c = f2(c,b)
    return c
print(f1(1,2))
#

I'd do something like this

wise falcon
#

youre right. wrong code

#

a=1 b=2 c=3 def f1(a,b,c): c+=a+b return c f1(a,b,c) c+=1 print(c)

neon idol
#

Ah okay so yeah. You'd do this

#
a=1
b=2
c=3
def f1(a,b,c):
    c+=a+b
    return c
c = f1(a,b,c)
c+=1
print(c)
wise falcon
#

but what if I want to change more than 1 variables ?

#

isnt globals the way?

neon idol
#

Globals are typically considered bad, you don't really want to be just changing global variables in functions, it's hard to keep track of and tracking down bugs/issues becomes more difficult

wise falcon
#

also read that I dont really need to specify arguments on the def since they are already there

neon idol
#

What do you mean?

#
a = 1 
b = 2
c = 3

def add_5(n):
    return n + 5

a = add_5(a)
b = add_5(b)
c = add_5(c)

I can't really think of good examples off of the top of my head but if you wanted to do something like that with globals it'd get very unwieldy

#

It's also clear exactly what is happening

wise falcon
#

ok thanks