Python: User-Defined Functions

Introduction to Functions

Modules, or functions, are a group of statements in a program created to perform a specific task, e.g. calculate total meal cost, calculate overtime pay, display an employee, etc. Using functions within programs is considered a good programming technique for several reasons:

  1. It allows a top-own, divide-and-conquer technique where a large program is divided into sub-tasks.
  2. The code is more organized and easier to read and understand.
  3. Functions are efficient and allow code to be re-used (and not duplicated).
  4. Functions can facilitate easier and more efficient testing by allowing sub-tasks to be tested.
  5. Functions can speed up software development time by facilitating teamwork where different programmers can be assigned individual functions to code.

In order to perform their task and interact with the main part of a program, functions can have data passed into or out from them (or neither). How one writes a function in this manner depends on the needs of the program and function and style of the programmer. Below are the four main ways a function may be used:

  1. No data passed in, no data passed out
  2. No data passed in, data passed out
  3. Data passed in, no data passed out
  4. Data passed in, data passed out

Example: No data passed in, no data passed out


	def menu():
	   print ("MAIN MENU")
	   print ("-----------------")
	   print ("1. Print pay checks")
	   print ("2. Look up employee")
	   print ("3. Change benefits")
	   print ("4. Exit")

	# Main part of progam
	menu()
	

User-defined functions should all be created and placed at the top of the program.

When the program above runs, the first line that is run is the menu() line, which calls the menu() function and displays the menu. The empty () indicate no data is being passed in to the function. You can think of the menu() line as the beginning of the main part of the program as languages such as C refer to it.

The line def menu(): is the function header. menu is the function name and the () indicates no data I being passed into the function. The name of function should always be descriptive and follow similar rules as variable names, e.g. no spaces, etc The six print statements are the function body.


Example: No data passed in, no data passed out


	def calculateAmountOwed():
		credits = int(input("How many credit hours will you be taking?"))
		amount_owed = credits*100+50
		print("Your total tuition amount is", amount_owed, "dollars.")

	calculateAmountOwed()
	

Example: No data passed in, data passed out

In the example below, no data is being passed into the function, but there is data being passed back out of the function. The variable choice is being passed back out of the function back into the main part of the program.


	def menu():
	   print ("MAIN MENU")
	   print ("-----------------")
	   print ("1. Print pay checks")
	   print ("2. Look up employee")
	   print ("3. Change benefits")
	   print ("4. Exit")
	   choice = int(input("Choose: "))
	   return choice

	choice = menu()
	print("You chose menu option", choice)
	

Output:

  MAIN MENU
  -----------------
  1. Print pay checks
  2. Look up employee
  3. Change benefits
  4. Exit
  Choose: 3
  You chose menu option 3

Thus, two things are needed to change a function so that data is passed out. First, the function needs to be called differently. This line indicates a variable choice will be returned from the function.

choice = menu()

And this line must be accompanied by a return statement in the function.

return choice


Variable scope, arguments, and parameters

When creating programs with functions, the concept and practice of variable scope is essential to understand. Variables can have either local or global score. Below is a distinction between the two.

  • Local scope. Typically, variable created within a function are only visible and available for use inside the function. When the function is over and control returned to them main part of program, the local variable in the function no longer exists. Local variables are variables said to have limited scope. The use of local variables is encouraged to avoid losing track of all of the locations within a large program were the value stored in a variable may be changed making the program perform in unexpected ways and also difficult to debug.
  • Global variables. In contrast, global variables are those that can be accessed from anywhere in the program – the main area or any function. Their scope is not limited. The minimal use of global variables is often recommended.

Example: Example of local variable scope

The following program demonstrates local scope. Because the variable total only exists in the user-defined function and is not passed back to the main part of the program, the last line of the program (i.e. the print statement) produces and fatal program error.


	def power3( arg1, arg2 ):
		 total = arg1 ** arg2;   # Local variable.
		 print ("Inside the function local total: ", total)

	power3( 10, 3 )    # Call power3 function
	print ("Value of total outside function: ", total)
	

Output:

  Inside the function local total: 1000
  Traceback (most recent call last):
  File "D:/Python Examples/temp.py", line 6, in
  print ("Value of total outside function: ", total)
  NameError: name 'total' is not defined


Example: Global Variables (do not use this method)

Global variables can be used to work around local scope, but this method is generally strongly discouraged as it makes programs more difficult to read and debug.


	def power3( arg1, arg2 ):
		 global total
		 total = arg1 ** arg2;   # Local variable.
		 print ("Inside the function local total: ", total)

	power3( 10, 3 )    # Call power3 function
	print ("Value of total outside function: ", total)
	

Output:

  Inside the function local total: 1000
  Value of total outside function: 1000


Example: Data passed in, data passed out

Instead of a global variables, simply pass the variable back to the main.


	def power3( arg1, arg2 ):
		 total = arg1 ** arg2;   # Local variable.
		 print ("Inside the function local total: ", total)
		 return total

	total = power3( 10, 3 )    # Call power3 function
	print ("Value of total outside function: ", total)
	

Output:

  Inside the function local total: 1000
  Value of total outside function: 1000

In the example above, the values 10 and 3 are known as arguments, which are any values passed into a function. The variables arg1 and arg2 are known as parameters, which are any values accepted into the function. In other words, values going into a function as arguments; once in the function, they are known as parameters. In many languages, the data type of the argument and parameter must be the same, or an error will occur.


Example: Data passed in, no data passed out


	# Function definition
	def printme(str):
		 print (str)

	# Main - function calls
	printme("This is the first line to be printed.")
	printme("This is the second line.")
	

Output:

  This is the first line to be printed.
  This is the second line.


Example: Data passed in, no data passed out


	def power3( arg1, arg2 ):
		 # raise arg1 to the power of arg2
		 total = arg1 ** arg2;   
		 print ("Inside the function local total: ", total)

	power3(3,2)
	

Output:

  Inside the function local total: 1000


Example: Data being passed into function, no data being passed back with keyword arguments


	def display_employeee( name, age ):
	   print ("Name: ", name, "\t Age: ", age)

	display_employeee( age=42, name="Daniel Smith" )
	display_employeee( age=35, name="Tina Jones" )
	

Output:

  Name: Daniel Smith      Age: 42
  Name: Tina Jones          Age: 35


Example: Data being passed into function, no data being passed back



Example: Data being passed into function, no data being passed back


	def calculateAmountOwed(credits):
		amount_owed = credits*100+50
		print("Your total tuition amount is", amount_owed, "dollars.")

	credits = int(input("How many credit hours will you be taking?"))
	calculateAmountOwed(credits)
	

Example: Data passed in, data passed out


	def calculateAmountOwed(credits):
		amount_owned = credits*100+50
		return amount_owned

	credits = int(input("How many credit hours will you be taking?"))
	amount_owned = calculateAmountOwed(credits)
	print("Your total tuition amount is", amount_owned, "dollars.")
	

Example: Global variable (not recommended)


	def calculateAmountOwed():
		global amount_owed
		credits = int(input("How many credit hours will you be taking?"))
		amount_owed = credits * 100 + 50

	calculateAmountOwed()
	print("Your total tuition amount is", amount_owed, "dollars.")
	

Example: Global variable (not recommended)


	def addHours():
	   global hours
	   hours_more = int(input('How many more hours did you work this week? '))
	   hours = hours + hours_more
	   print ("You've worked ", hours, " hours")

	hours = 0
	hours = int(input('How many hours did you work so far this week? '))
	addHours()
	print ("You've worked ", hours, " hours")
	

Output:

  How many hours did you work so far this week? 20
  How many more hours did you work this week? 20
  You've worked 40 hours
  You've worked 40 hours


Example: Alternative to previous example


	def addHours(hours):
	   hours_more = int(input('How many more hours did you work this week? '))
	   hours = hours + hours_more
	   return hours

	hours = 0
	hours = int(input('How many hours did you work so far this week? '))
	newhours = addHours(hours)
	print ("You've worked ", newhours, " hours")
	


Example: Function with Data Passed In and Data Passed (Returned) Out