-3

Can some please explain to me this code

def zap():
    print stype

def main():
    if True:
        stype="something"
        zap()     
    else:
        stype="something else"

if __name__ == '__main__':
    main()

stype is already defined before I called zap function

But I'm getting this error.

Traceback (most recent call last):
  File "C:\Users\x126\Desktop\ss.py", line 12, in <module>
    main()
  File "C:\Users\x126\Desktop\ss.py", line 7, in main
    zap()
  File "C:\Users\x126\Desktop\ss.py", line 2, in zap
    print stype
NameError: global name 'stype' is not defined
  • 1
    It's not defined. You're defining it within the scope of the main function, not globally. – Matt Fletcher Dec 30 '17 at 14:08
  • Apparently written by someone that forgot about *scopes*. – Willem Van Onsem Dec 30 '17 at 14:08
  • Why not just pass stype through the parameters of zap? – Matt Fletcher Dec 30 '17 at 14:09
  • there is also the `global` keywoard which you can use to elevate something to the global scope (and clutter it) - the saner way would be to use a parameter in the function and pass it that-a-way to it. Have a look [here](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them) for more infos – Patrick Artner Dec 30 '17 at 14:12

2 Answers2

4

That's not how it works. stype isn't available in zap just because it was defined somewhere else before you called the function. You'll need to pass it in explicitly:

def zap(stype):
    print stype

if True: # Of course this is unnecessary 
        stype="something"
        zap(stype)

Or you could make it a global; although that's not recommended. Always prefer making necessary data a parameter instead of a global, as abuse of globals tends to complicate programs in the long-term.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
0

To use global variable:

stype ="ori"

def zap():
    print (stype)

def main():
    global stype
    if True:
        stype="something"
        zap()    
    else:
        stype="something else"

if __name__ == '__main__':
    main()

Output:

something
rnso
  • 23,686
  • 25
  • 112
  • 234