Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – returning multiple values from a function


Tuples are often used to return multiple values from a Python function. Let's create a simple function that takes the x, y, and z components of a Euclidean vector and returns the unit vector that points in the same direction.

def get_unit_vector(x, y, z):
    """
    Returns the unit vector that is codirectional with 
    the vector with given x, y, z components.
    This function uses a tuple to return multiple values.
    """
    norm = sqrt(x**2 + y**2 + z**2)
    return x / norm, y / norm, z / norm
    
x = 3.434
y = -2.1
z = 7.991

unit_x, unit_y, unit_z = get_unit_vector(x, y, z)

print("Unit vector:")
print("x: " + str(unit_x) + " y: " + str(unit_y) +
    " z: " + str(unit_z))
print("Norm: " + str(sqrt(unit_x**2 + unit_y**2 + unit_z**2)))

Execute the code. The results should look like this:

What just happened?

This example demonstrated how to return multiple values from a function. The function definition should be familiar...