Python - Function Definitions and Calls

Definition

The following code defines a function called times, which returns the product of its two arguments:

def times(x, y):       # Create and assign function 
    return x * y       # Body executed when called 

Calls

The def statement makes a function but does not call it.

After the def has run, you can call the function by adding parentheses after the function's name.

The parentheses may optionally contain one or more object arguments, to be passed to the names in the function's header:

times(2, 4)            # Arguments in parentheses 

This expression passes two arguments to times.

Arguments are passed by assignment, the name x in the function is assigned the value 2, y is assigned the value 4.

Demo

def times(x, y):       # Create and assign function 
    return x * y       # Body executed when called 
# from   w ww.  j  a v  a 2s. co m
x = times(2, 4)            # Arguments in parentheses 
print( x )

x = times(3.14, 4)     # Save the result object 
print( x )

Result

The function is called a third time with different kinds of objects passed in:

Demo

def times(x, y):       # Create and assign function 
    return x * y       # Body executed when called 
# from  ww  w  .j  a  va2  s  .  c  o  m
x = times('Ni', 4)         # Functions are "typeless" 
print( x )

Result

In this third call, a string and an integer are passed to x and y, instead of two numbers.

* works on both numbers and sequences.

Related Topics