Your students have already used functions in various Python programs they have written and seen. The most common functions used include range, len, int, and sqrt. These four functions were invoked with at least one argument (the range function can have up to three arguments) and all returned a value or a list of values:
>>> range(5) [0, 1, 2, 3, 4] >>> range(3,8) [3, 4, 5, 6, 7] >>> range(5,31,5) [5, 10, 15, 20, 25, 30] >>> len([0,1,2,3,4]) 5 >>> a = "15" >>> x = int(a) >>> x 15 >>> import math >>> x = math.sqrt(16) >>> x 4.0
Functions have to be defined before they are called (or invoked). The function definition makes Python record the function and when the function is called, the first line of the function is executed. When all the statements in the function have been executed, Python returns to the place it was called from.
Below are three examples of functions which will be discussed later in this document:
A function with no arguments and no return statement:
## function printGreeting prints Good Morning! ## the function has no arguments and no return statement def printGreeting(): print("Good Morning!") ## function call printGreeting()
A function with one argument and no return statement:
## function printPersonalizedGreeting prints Good Morning ## the function has one argument and no return statement def printPersonalizedGreeting(name): print("Good Morning,", name) #function call printPersonalizedGreeting("John")
>>> Good Morning, John
A function with two arguments and a return statement:
## function calculateTax has two arguments ## It assumes implicitly that the second argument (rate) is between 0 and 100 ## After excluding the first $100 of amount, the tax is computed using ## rate and returned. def calculateTax(amount, rate): if amount <= 100: tax = 0 else: tax = (amount -100) * rate / 100 return tax ## calling the function print(calculateTax(500,2))
>>> 8