Functions

You use the def statement to create a function, as shown in the following example:

def remainder(a,b): 
        q = a/b 
        r = a - q*b 
        return r 

To invoke a function, simply use the name of the function followed by its arguments enclosed in parentheses, such as result = remainder(37,15). You can use a tuple to return multiple values from a function, as in the following example:

def divide(a,b): 
        q = a/b        # If a and b are integers, q is an integer 
        r = a - q*b 
        return (q,r) 

When returning multiple values in a tuple, it’s often useful to invoke the function as follows:

quotient, remainder = divide(1456,33) 

To assign a default value to a parameter, use assignment:

def connect(hostname,port,timeout=300): 
      # Function body 

When default values are ...

Get Python Essential Reference, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.