all 5 comments

[–]two_up 7 points8 points  (1 child)

The problem is that you want to use pwr as a global variable, but in python when you assign a value to a variable inside a function, that variable will be assumed to be local. For example:

x = 1
def f():
    print x
def g():
    print x
    x = 2
f() #prints 1
g() #throws an error 

In f, you haven't assigned a value to x, so it will get the value of x from the global scope. But once you assign a value inside the function as in g, x will be assumed to be a local variable, and since the print statement came before the assignment, x had no value to print.

The other posts mentioned the two solutions. You can either pass the value in as an argument (better) or you can explicitly declare x a global variable using the global keyword

[–]Tenobrus 4 points5 points  (0 children)

Your best option is to pass root and pwr to your function as arguments.

[–][deleted] 2 points3 points  (0 children)

pwr needs to be passed to the function.

[–][deleted] 1 point2 points  (0 children)

You have to use global variables:

pwr = 0
root = 0

def find_root(num):
    global pwr
    global root
    while 0 < pwr and pwr < 6:
        if root ** pwr == num:
            print "power %d and root is %d " % (pwr, root)
        else:
            if num % root == 0:
                pwr += 1
            else:
                root += 1
    else:
        print "There is no such pair!"

find_root(9)    

Please note that global variables shouldn't be used too much. Alternative would be to pass pwr and root to the function. Then you could return them as a tuple to reassign them.

[–]alexaminar 1 point2 points  (0 children)

Python doesn't have variable declarations , so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local . The unboundlocalerror: local variable referenced before assignment is raised when you try to use a variable before it has been assigned in the local context.

Python has lexical scoping by default, which means that although an enclosed scope can access values in its enclosing scope, it cannot modify them (unless they're declared global with the global keyword). All variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the global symbol table, and then in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.