[Tutor] Will the following code ever exit?

Nathan Pinno falcon3166 at hotmail.com
Sat Sep 17 03:25:30 CEST 2005

Thanks, but when I run the code, even after that change it always just 
prints the questions, correct questions(which is always 0), and percent 
right(always 0). How do I make it enter the quiz.
Nathan Pinno
----- Original Message ----- 
From: "John Fouhy" <john at fouhy.net>
To: "Nathan Pinno" <falcon3166 at hotmail.com>
Cc: <tutor at python.org>
Sent: Friday, September 16, 2005 7:20 PM
Subject: Re: [Tutor] Will the following code ever exit?

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!


More information about the Tutor mailing list