Sage Reference: Defining Functions


Function Definition

Mathematical functions, like \(f(x) = x^2\), can be created easily in Sage:

By default, Sage recognizes \(x\) as a variable. To define a function in more than one variable (or to use a variable other than \(x\)), you'll need to tell Sage what names you'll be using:

Another way to define a function:

We can use the same idea for more complicated functions. Pay particular attention to whitespace - each line within the definition of the function MUST be indented. Below we create a piecewise function using a simple if statement (more on these later).

An Example: What day of the week was it?

Read through the code below, which defines a function that takes three arguments (a month, day, and year) and returns the day of the week. The function makes extensive use of if statements and modular arithmetic.

The code is based on the algorithm described on Wikipedia. Enter a date in mm/dd/yyyy format (months and dates can be input as single or double digits).

Evaluate this cell first, to define the function. Nothing will be returned.

Then evaluate this cell, after entering a date. If you get an error, be sure you evaluated the cell above first - otherwise, the function 'day' hasn't been defined.