Description
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.
Code
def doubleMe(n)
return n*2
doubleMe(3)
Options
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.
Code
def powerMe(b, k=2):
return b^k
powerMe(2)
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:
Tags
Primary Tags—Programming: The Python language.
Secondary Tags—The Python language: Functions.
Related Cells
Attribute
Permalink:
Author:
Date: 11 Mar 2019 17:22
Submitted by: Zane Corbiere