First time here? Check out the FAQ!

Ask Your Question
1

How to make a function return a value

asked 10 years ago

anonymous user

Anonymous

updated 10 years ago

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)
Preview: (hide)

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 ( 10 years ago )

2 Answers

Sort by » oldest newest most voted
1

answered 10 years ago

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.

Preview: (hide)
link
1

answered 10 years ago

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
Preview: (hide)
link

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: 10 years ago

Seen: 2,198 times

Last updated: Jan 30 '15