[Tutor] Will the following code ever exit?

John Fouhy john at fouhy.net
Sat Sep 17 03:20:37 CEST 2005


On 17/09/05, Nathan Pinno <falcon3166 at hotmail.com> wrote:
> def add(a,b): 
>     answer = a+b 
>     guess = float(raw_input(a," + ",b," = ")) 

Hi Nathan,

When you define a function, any variables you create in the function
are _local_ variables.  This means that they only exist within the
function, and when the function exits, python will forget about them.

As an example, consider the following code:

###
total = 13

def add(a, b):
    total = a + b

add(2, 4)
print total
###

The print statement at the end will print out 13, not 6.  The best way
to get output from a function is to use a return statement.  So, we
could change your add function to look something like this:

###
def add(a, b):
    answer = a+b
    guess = float(raw_input(a," + ",b," = "))
    return answer, guess
###

Then, you can use the function in your program like this:

###
answer, guess = add(num1, num2)
###

This will get the return values of the function and put it into
variables which you can access from the rest of your program.

Hope this helps!

-- 
John.


More information about the Tutor mailing list