Untitled Document
Untitled Document
Objectives: (at the end of the of the activity, the students will be able to)
1. Define new functions in Python.
2. Write programs that use functions to reduce code duplication and increase program
modularity.
Equipment
Quantity
2 PC per students with python IDE
Basic Concepts:
Introduction to function
CONCEPT: A function is a group of statements that exist within a program for the purpose of performing a
specific task. In the previous activities, we described a simple algorithm for calculating an employee’s
pay. In the algorithm, the number of hours worked is multiplied by an hourly pay rate. A more realistic
payroll algorithm, however, would do much more than this. In a real-world application, the overall task of
calculating an employee’s pay would consist of several subtasks, such as the following:
A program that has been written with each task in its own function is called a modularized program.
Introduction to Functions
1. What is a function?
- A function is a group of statements that exist within a program for the purpose of performing a
specific task.
3. When a function is executing, what happens when the end of the function’s block is reached?
- The interpreter jumps back to the part of the program that called the function, and the program
resumes execution at that point.
2. What are the variables that receive pieces of data in a function called?
- Parameter.
4. When a parameter is changed, does this affect the argument that was passed into the
parameter?
- It changes made to the parameter will affect the argument used to call the subroutine.
5. The following statements call a function named show_data. Which of the statements passes
arguments by position, and which passes keyword arguments?
a. show_data(name='Kathryn', age=25)
b. show_data('Kathryn', 25)
- A passes keyword arguments, while B passes arguments by position.
Global Constants
1. What is the scope of a global variable?
- it is visible (hence accessible) throughout the program, unless shadowed.
2. Give one good reason that you should not use global variables in a program.
- The reason is to protect data and members of classes from being changed, inadvertently or on
purpose, by other parts of the program.
Generalization:
Today’s task is to program a topic function. Function programming is all about static truths such as in
Math, is easier to reason about, is tractable, and in a lot of places solves our problems better than
imperative solutions.
References:
[1]
chegg, “‘Starting Out With Python’: Ch. #3 Flashcards | Chegg.com,” www.chegg.com, Apr. 13,
2023. https://www.chegg.com/flashcards/starting-out-with-python-ch-3-9a40482e-6e02-45aa-
89e7-bf8689a2ded6/deck (accessed Apr. 13, 2023).
[2]
quizlet, “Starting Out with Python, 3e Ch 5,” quizlet, Apr. 13, 2023.
https://quizlet.com/442988869/starting-out-with-python-3e-ch-5-flash-cards/ (accessed Apr. 13,
2023).