Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for Blaec (CSO) Tasks and Strategy Outline.
Download

Tutorial Release 10.4 The Sage Development Team https://doc.sagemath.org/pdf/en/tutorial/sage_tutorial.pdf

Sage is free, open-source math software that supports research and teaching in algebra, geometry, number theory, cryptography, numerical computation, and related areas. Both the Sage development model and the technology in Sage itself are distinguished by an extremely strong emphasis on openness, community, cooperation, and collaboration: we are building the car, not reinventing the wheel. The overall goal of Sage is to create a viable, free, open-source alternative to Maple, Mathematica, Magma, and MATLAB.

This tutorial is the best way to become familiar with Sage in only a few hours. You can read it in HTML or PDF versions, or from the Sage notebook (click Help, then click Tutorial to interactively work through the tutorial from within Sage).

This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

https://creativecommons.org/licenses/by-sa/3.0/

386 views
ubuntu2204
Kernel: SageMath 10.4

2.3 Functions, Indentation, and Counting

To define a new function in Sage, use the def command and a colon after the list of variable names.

For example:

def is_even(n): return n % 2 == 0
is_even(2)
True
is_even(3)
False
from sage.all import * def is_even(n): return n % Integer(2) == Integer(0)
is_even(Integer(2))
True
is_even(Integer(3))
False

Note: Depending on which version of the tutorial you are viewing, you may see three dots ....: on the second line of this example. Do not type them; they are just to emphasize that the code is indented. Whenever this is the case, press [Return/Enter] once at the end of the block to insert a blank line and conclude the function definition.

You do not specify the types of any of the input arguments. You can specify multiple inputs, each of which may have an optional default value. For example, the function below defaults to divisor=2 if divisor is not specified.

def is_divisible_by(number, divisor=2): return number % divisor == 0
is_divisible_by(6, 2)
True
is_divisible_by(6)
True
is_divisible_by(6, 5)
False
from sage.all import * def is_divisible_by(number, divisor=Integer(2)): return number % divisor == Integer(0)
is_divisible_by(Integer(6), Integer(2))
True
is_divisible_by(Integer(6))
True
is_divisible_by(Integer(6), Integer(5))
False

You can also explicitly specify one or either of the inputs when calling the function; if you specify the inputs explicitly, you can give them in any order:

is_divisible_by(6, divisor=5)
False
is_divisible_by(divisor=2, number=6)
True
from sage.all import * is_divisible_by(Integer(6), divisor=Integer(5))
False
is_divisible_by(divisor=Integer(2), number=Integer(6))
True