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 – introducing the Python decorator


Enter the following code into a cell in a workbook and run it. You can also run this on the Sage command line, but the HTML formatting will not look nice!

def html_table(func):
    
    def display_output(*args):
        result = func(*args)
        html_string = '<table border=1><tr>'
        for item in result:
            html_string += '<td>' + str(item) + '</td>'
        html_string += '</tr></table>'
        html(html_string)
        return result
        
    return display_output
    
@html_table
def square_list(my_list):
    for i in range(len(my_list)):
        my_list[i] = my_list[i]**2
    return my_list
    
x = square_list([1.0, 2.0, 3.0])
print x

The result should be:

What just happened?

We defined a simple function called square_list, that accepts a list as an argument, squares every item in the list, and returns the squared list. Since you've just been introduced to NumPy, you should recognize...