Ask coding questions

← Back to all posts
why is it showing namechoice as undefined
kbadrinath_tcsp (222)

so basically i'm making this thing, and when i try to use namechoice in firstStretch(), it just keeps on saying that namechoice is undefined. I have tried making namechoice global both in and out of the function, and other things, but it is not working. any suggestions?

Answered by ChezCoder (1614) [earned 5 cycles]
View Answer
Comments
hotnewtop
ChezCoder (1614)

global is for accessing variables while the code is in a function. You have to do it the other way around.

basically, here is an example:

This doesnt work

global foo
foo = "bar"

def baz():
    print(foo)

This works

foo = "bar"

def baz():
    global foo # this tells python that foo is outside of the function
    print(foo)
kbadrinath_tcsp (222)

but the thing is, I am only declaring namechoice in a function. should I just have that outside of a function in the code? @ChezCoder

ChezCoder (1614)

@kbadrinath_tcsp unless you want namespace to be only in that function, yes, declare it outside.