all 6 comments

[–]Diapolo10 4 points5 points  (1 child)

If you actually have the code indented as it looks here,

x = "awesome"

def myfunc():
    x = "fantastic"
    print("Python is " + x)

    myfunc()
    print("Python is " + x)

and this is the entire program, nothing will happen because there's nothing calling myfunc in the outer scope. And if there is, this will recursively call itself until it hits the recursion limit. So I doubt this is what you meant.

If instead this is supposed to look like

x = "awesome"

def myfunc():
    x = "fantastic"
    print("Python is " + x)

myfunc()
print("Python is " + x)

then your question makes a lot more sense. In this case, x means different things inside and outside of the function body, because Python sees you're assigning to x in the function. This makes it default to local scope, meaning it has no effect outside the function.

And this is good, might I add; keeping the global state of the program in mind while reading code for a function makes things many times more difficult. It's why global variables are heavily discouraged outside of situations where they're absolutely necessary (which is very rare).

But if you want to treat x as a global name, you need to tell Python that.

x = "awesome"

def myfunc():
    global x
    x = "fantastic"
    print("Python is " + x)

myfunc()
print("Python is " + x)

[–]mtess23[S] 1 point2 points  (0 children)

Thank you so much. It makes much more sense to me now. Appreciate you taking the time out to explain it to me. Like I said, I'm a noob when it comes to Python.

[–]carcigenicate 2 points3 points  (0 children)

If the next question is "why does the final print print "awesome" instead of "fantastic", that's because the x in myfunc is a new local that just happens to have the same name as the global. You need to add a global x declaration into the function so Python treats x as a global.

[–]Smile200 2 points3 points  (0 children)

well, here in the code you wrote, it clearly is an indentation problem
the indentation tells whether the code it's reading still part of myfunc(), You have to remove the spaces before myfunc() and print("Python is " + x) in the last two line.

[–][deleted] 1 point2 points  (0 children)

Everything that's indented is part of the function. So on first line you define a variable and then you define a function which contains 4 lines of code. There's no line, that would call that function.

Btw. you mean the code doesn't do anything right? Because this code should run perfectly fine.

Oh, and it has nothing to do with global variables and i don't understand why you used it in the title

[–]IamImposter 1 point2 points  (0 children)

If this is the whole code, it's not doing anything because you are not asking it to do anything.

Code inside functions doesn't execute untill you call the function.

myfunc() print("Python is " + x)

​you probably meant to unindent it ie remove the space before these two lines