User-defined Functions, Parameters and Arguments

50 min read Functions

This is a free course. Log in to run the code exercises and track your progress.

User-defined Functions, Parameters and Arguments

Python has three kinds of functions: built-in functions (len(), print()), functions defined in modules (math.sqrt()), and user-defined functions that you write with def.

def area(length, breadth=1):     # length, breadth: parameters
    return length * breadth

print(area(5, 3))                # 15: positional arguments
print(area(5))                   # 5: breadth takes its default value
print(area(breadth=4, length=2)) # 8: keyword arguments, any order

The names in the def line are parameters (formal parameters); the values in a call are arguments (actual parameters).

  • Positional arguments are matched to parameters by their position.
  • Default parameters have a value used when the argument is left out. They must come after all the parameters without defaults: def f(a=1, b) is a syntax error.
  • Keyword arguments name the parameter, so their order does not matter. In a call, positional arguments must come before keyword arguments.
Python exercise

Complete simple_interest(principal, rate=5, time=1) so it returns the simple interest. The program calls it with all three arguments, with only the principal, and with keyword arguments, and prints the three results.

def simple_interest(principal, rate=5, time=1):
    return 0.0  # principal * rate * time / 100


p, r, t = map(float, input().split())
print(simple_interest(p, r, t))
print(simple_interest(p))
print(simple_interest(time=2, principal=p))

Log in to edit and run this code.