1
print 'Welcome to the Pig Latin Translator!'

def pyg():
    if name.isalpha and len(name) > 0:
        print
    elif name.isdigit:
        print "This is an integer, not a string!"
        name = raw_input()
        pyg()
    elif len(name) <= 0:
        print "You typed nothing!"
        name = raw_input()
        pyg()
name = raw_input()
pyg()        

So I get the error

UnboundLocalError: local variable 'name' referenced before assignment

What I'm trying to do is when my input name is an integer I enter something to replace name and run the function again

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
Ch3wbacc4
  • 35
  • 5

2 Answers2

5

Why don't you pass the name as an argument to the function, and make the function accept the parameter?

print 'Welcome to the Pig Latin Translator!'

def pyg(name):
    if name.isalpha() and len(name) > 0:
        print
    elif name.isdigit():
        print "This is an integer, not a string!"
        name = raw_input()
        pyg()
    elif len(name) == 0:
        print "You typed nothing!"
        name = raw_input()
        pyg(name)

name = raw_input()
pyg(name)

BTW, the code is missing () after isalpha, isdigit. and the length will never become negative number. len(name) < 0 does not make sense.

falsetru
  • 357,413
  • 63
  • 732
  • 636
0

This is a problem with variable scoping. Python takes an approach to function scopes and conflicts that is different than most languages. If you are only reading the variable, it will use the global version. However, if you try to set it, it will then the use local version.

The python interpreter sees that you are setting name = raw_input() down at the bottom, and uses the local version, throughout the function. Since the local one isn't initialized the first time, you get an error. So to fix it, you just have to force python to use the global one, with this line:

def pyg():
    global name

    . . .

Of course, the suggestions other have given you are much better practice, and are what you should be using.

Community
  • 1
  • 1
Maltysen
  • 1,868
  • 17
  • 17
  • Thanks now my code works but I still don't understand when I should use "global" – Ch3wbacc4 Aug 01 '15 at 08:11
  • 2
    @Ch3wbacc4 Rarely, if ever. There's often a better solution than `global`, take a look at mine and falsethu's answers. Global variables can often have side effects you didn't realize, if something else is modifying the variable between your function call, for example. – Markus Meskanen Aug 01 '15 at 08:14