# How to make a function return a value Anonymous

I'm writing a Sage Function for the Euclid's Algorithm. However when I run it, it doesn't compute any values. Please let me know what is wrong or anyway to help.

 def euclide(a,b):
r=a%b
print (a,b,r)
while r !=0:
a=b; b=r
r=a%b
print (a,b,r)

sage: euclide(12,5)
(12, 5, 2)
(5, 2, 1)
(2, 1, 0)

edit retag close merge delete

I shortened the title of your question, and put the longer version as the text of your question, together with the code. By the way the answer is given by @kcrisman (I changed it from a comment to an answer).

Sort by » oldest newest most voted

To complement @kcrisman's answer: the code you gave looks like a "debugging" version, with the print statements.

I suppose you would want to comment out the print statements and make the function return the result.

def euclide(a,b):
r=a%b
# print (a,b,r)
while r !=0:
a=b; b=r
r=a%b
# print (a,b,r)
return b


Then you would get:

sage: euclide(12,5)
1


Or you could introduce an extra (optional) argument to your function to decide whether to print steps.

def euclide(a,b,verbose=False):
r=a%b
if verbose:
print (a,b,r)
while r !=0:
a=b; b=r
r=a%b
if verbose:
print (a,b,r)
return b


Then you could do:

sage: euclide(12,5)
1
sage: euclide(12,5,verbose=True)
(12, 5, 2)
(5, 2, 1)
(2, 1, 0)
1

more

Exactly what seems to not be working? It is printing out what you ask it to. If you want it to return values for further use and not just print them, that is a little different - you will have to use the return statement.

more