Defining Subroutines and Functions


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—Programming: The Python language.

Secondary Tags—The Python language: Functions.

Related Cells




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