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 – defining a function with keyword arguments


Let's re-define our function with keyword arguments:

def RC_voltage(t, v0=100, R=1000, C=1e-9):
    """
    Calculate the voltage at time t for an R-C circuit
    with initial voltage v0.
    """
    tau = R * C
    return v0 * exp(-t / tau)
    
res = 250e3   # Ohms
cap = 4e-6    # Farads
v0 = 100.0    # Volts
t = 1.0      # seconds

v = RC_voltage(t, v0=v0, R=res, C=cap)
print('Voltage at t=' + str(n(t, digits=4)) + 's is ' + 
    str(n(v, digits=4)) + 'V')

The output is the same as the previous example.

What just happened?

Declaring keyword arguments is very similar to declaring positional arguments. If there are keyword arguments, they must be defined after the positional arguments. The default value of each keyword argument must be given. The following is the general form of a function definition with positional and keyword arguments:

def function_name(argument_1, argument_2, … , argument_n,
   keyword_arg_1=default_value,…...