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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Thanks now my code works but I still don't understand when I should use "global"
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.