4

So this is a piece of the code:

global episode = "Episode404"
import testing
reload (testing)
#or
python testing.py

testing.py:

def doIt():
    print episode
doIt()

And this throws me

# Error: invalid syntax # 

I'm guessing this is because I'm trying to pass a global variable and run? How can I fix this?

Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
Jozef Plata
  • 350
  • 4
  • 11
  • 1
    Post the whole stack trace. I suspect that you're not calling print appropriately. Either you run python3 or you've imported ```print_function``` from future – Anis Jul 24 '17 at 14:00
  • 1
    not really. thats all. Im running python 2.7 – Jozef Plata Jul 24 '17 at 14:48

2 Answers2

2

The line below is wrong:

global episode = "Episode404"

But you are also misunderstanding the concept of global command. You need to use it to change the value of some variable defined outside of the scope that you are currently working.

What Andy answered works, but it is not necessary, as you can do this with the same result:

episode = "Episode404"

def doIt():
    print(episode)

doIt()

global here would be only necessary if you want to change the value of episode inside doIt() with this change being propagated outside of the scope of doIt() like this:

episode = "Episode404"

def doIt():
    global episode
    print(episode)
    episode = "New Episode"

doIt()
print(episode)

and the output will be:

"Episode404"
"New Episode"

If you really need to use different modules, why don't you just pass the episode as an argument for doIt()?

Put this on your testing.py

def doIt(episode):
    print(episode)

And then change your main code to:

from testing import doIt

episode = "Episode404"
doIt(episode)

I think this approach is better than using global variables and trying to share them between modules. Probably you can do that only using hacks or things that you probably don't need.

0

I suppose Python doesn't have a way to specify a variable in a module that's global to all namespaces. Try to declare a variable this way:

import testing

global episode
episode = "Episode404"

def doIt():
    print(episode)

doIt()

Here's good example how to use variables globally and locally in Python.

Andy Jazz
  • 49,178
  • 17
  • 136
  • 220