[prog] quick question on Python
Mary
mary-linuxchix at puzzling.org
Sun Dec 8 15:32:46 EST 2002
On Sun, Dec 08, 2002, Guru - wrote:
> Regrading this function:
> def euclid(a,b):
> while b:
> a,b = b,a % b
> print "Common factor is", a
> return a
Wouldn't the syntax have to be:
def euclid(a,b):
while b:
a,b = b,a % b
print "Common factor is", a
return a
?
> With the return a....I'm confused on what exactly it does. Becuase if
> I said print (after using the function) "This is the answer", a. a
> wouldn't be the variable that was found inside the function. So what
> exactly does the return do, besides end the function?
The return value can be assigned to something outside a function.
For example,
I could simply write a piece of code that called your method:
euclid(6, 3)
which will make no use of the return value.
Or, since euclid returns a value, I can assign a variable to that value:
b = euclid(6, 3) # b is now the value that was returned, that is:
# b is equal to euclid's a variable
Or I could print it:
print "the greatest common divisor of %d and %d is %d\n" % (6, 3, euclid(6, 3))
That is, because euclid returns a value, I can treat a call to euclid
like it is a variable.
-Mary
More information about the Programming
mailing list