Ch3wbacc4
Ch3wbacc4

Reputation: 35

How do I replace a variable in a if statement in a function?

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

Upvotes: 1

Views: 580

Answers (2)

Maltysen
Maltysen

Reputation: 1946

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.

Upvotes: 0

falsetru
falsetru

Reputation: 369054

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.

Upvotes: 5

Related Questions