Defining Subroutines


Here, we will define a simple subroutine in Sage that multiplies a number by 2 and returns the result

Sage Cell

We indicate to sage that we're creating a subroutine with the def keyword. After this, we declare the subroutine's name (doubleMe) and parameters (n). What follows is the code for our subroutine—we indicate that it is being used in the sub by indenting it. Here we only have one line, in which we return the doubled value of n. Note that the subroutine immediately terminates after the return statement is completed, so any lines after it will not be executed.


def doubleMe(n)
    return n*2



Optional Parameters

When declaring a subroutine, we can make certain parameters optional by setting a default value. This is done by setting the parameter equal to a value in the declaration:

powerMe() will now return 16, because we have overriden the default value of k for this call.


def powerMe(b, k=2):
    return b^k

powerMe(2, 4)

Order of parameters

Say we make a subroutine with a large amount of parameters, and forget the order in which they are defined. If we use their names to define them, we can define them in any order within the parentheses:


Primary Tags:

Secondary Tags:

A list of possible tags can be found at The WeBWorK Open Problem Library. For linear algebra tags see the Curated Courses Project.

Related Cells

Any related cells go here. Provide a link to the page containing the information about the cell.




Date: 11 Mar 2019 17:22

Submitted by: Zane Corbiere

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License