Ask Your Question
1

How to make a function return a value

asked 2015-01-29 03:35:55 +0100

anonymous user

Anonymous

updated 2015-01-29 15:32:57 +0100

slelievre gravatar image

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 flag offensive close merge delete

Comments

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).

slelievre gravatar imageslelievre ( 2015-01-29 15:34:52 +0100 )edit

2 Answers

Sort by ยป oldest newest most voted
1

answered 2015-01-29 05:48:41 +0100

kcrisman gravatar image

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.

edit flag offensive delete link more
1

answered 2015-01-30 12:26:27 +0100

slelievre gravatar image

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
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2015-01-29 03:35:55 +0100

Seen: 2,098 times

Last updated: Jan 30 '15