Amat111 CH 4 Functions
Amat111 CH 4 Functions
Functions
AIM
Learn to de ne and invoke functions and comprehend the use of arguments and
parameters to pass information to a function as well as return information from a
function.
LEARNING OUTCOMES
At the end of this chapter, you are expected to
Functions are one of the fundamental building blocks in Python programming language.
Functions are used when you have a block of statements that needs to be executed mul-
tiple times within the program. Rather than writing the block of statements repeatedly to
perform the action, you can use a function to perform that action. This block of statements
are grouped together and is given a name which can be used to invoke it from other parts
of the program. You write a function once but can execute it any number of times you like.
Functions also reduce the size of the program by eliminating rudimentary code. Functions
can be either Built-in Functions or User-de ned functions.
95
96 Introduction to Python Programming
TABLE 4.1
A Few Built-in Functions in Python
Function Name Syntax Explanation
For example,
1. >>> abs(-3)
3
2. >>> min(1, 2, 3, 4, 5)
1
3. >>> max(4, 5, 6, 7, 8)
8
4. >>> divmod(5, 2)
(2, 1)
5. >>> divmod(8.5, 3)
(2.0, 2.5)
6. >>> pow(3, 2)
9
7. >>> len("Japan")
5
Keyword
import module_name
1. >>>import math
The math module is part of the Python standard library which provides access to various
mathematical functions and is always available to the programmer ➀.
The syntax for using a function de ned in a module is,
module_name.function_name()
Import the math module at the beginning ➀. The math.ceil(x) function returns the ceiling
of x, the smallest integer greater than or equal to the number ➁, math.sqrt(x), returns the
square root of x ➂, math.pi is the mathematical constant π = 3.141592…, to available preci-
sion ➃, math.cos(x) returns the cosine of x radians ➄, math.factorial(x) returns x factorial ➅,
math.pow(x, y) returns x raised to the power y ➆.
98 Introduction to Python Programming
The built-in function dir() returns a sorted list of comma separated strings containing
the names of functions, classes and variables as de ned in the module. For example, you
can nd all the functions supported by the math module by passing the module name as
an argument to the dir() function.
1. >>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin',
'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp',
'expm1', 'fabs', 'factorial', ' oor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf',
'isclose', 'is nite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf',
'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
1. >>> help(math.gcd)
Help on built-in function gcd in module math:
gcd(…)
gcd(x, y) -> int
greatest common divisor of x and y
Another useful module in the Python standard library is the random module which gen-
erates random numbers.
First, you need to import the random module to use any of its functions ➀. The random()
function generates a random oating-point number between 0 and 1 and it produces a
different value each time it is called ➁. The syntax for random.randint() function is ran-
dom.randint(start, stop) which generates a integer number between start and stop argument
numbers (including both) ➂.
Third-party modules or libraries can be installed and managed using Python’s package
manager pip.
The syntax for pip is,
Arrow is a popular Python library that offers a sensible, human-friendly approach to cre-
ating, manipulating, formatting and converting dates, times, and timestamps.
To install the arrow module, open a command prompt window and type the below com-
mand from any location.
UTC is the time standard commonly used across the world. The world’s timing centers
have agreed to keep their time scales closely synchronized—or coordinated—therefore
the name Coordinated Universal Time ➁. Current date including time is displayed using
now() function ➂.
Indentation statement(s)
Colon should be present at
the end
1. The name of the function. The function’s name has to adhere to the same naming
rules as variables: use letters, numbers, or an underscore, but the name cannot
start with a number. Also, you cannot use a keyword as a function name.
2. A list of parameters to the function are enclosed in parentheses and separated by
commas. Some functions do not have any parameters at all while others may have
one or more parameters.
100 Introduction to Python Programming
3. A colon is required at the end of the function header. The rst line of the function
de nition which includes the name of the function is called the function header.
4. Block of statements that de ne the body of the function start at the next line of the
function header and they must have the same indentation level.
The def keyword introduces a function de nition. The term parameter or formal param-
eter is often used to refer to the variables as found in the function de nition.
The rst statement among the block of statements within the func-
tion de nition can optionally be a documentation string or docstring.
There are tools which use docstrings to produce online documents or
printed documentation automatically. Triple quotes are used to repre-
sent docstrings. For example,
""" This is single line docstring """
OR
""" This is
multiline
docstring """
De ning a function does not execute it. De ning a function simply names the function
and speci es what to do when the function is called. Calling the function actually per-
forms the speci ed actions with the indicated parameters.
The syntax for function call or calling function is,
function_name(argument_1, argument_2,…,argument_n)
Arguments are the actual value that is passed into the calling function. There must be
a one to one correspondence between the formal parameters in the function de nition
and the actual arguments of the calling function. When a function is called, the formal
parameters are temporarily “bound” to the arguments and their initial values are assigned
through the calling function.
A function should be de ned before it is called and the block of statements in the func-
tion de nition are executed only after calling the function. Normally, statements in the
Python program are executed one after the other, in the order in which they are written.
Function de nitions do not alter the ow of execution of the program. When you call a
function, the control ows from the calling function to the function de nition. Once the
block of statements in the function de nition is executed, then the control ows back to the
calling function and proceeds with the next statement. Python interpreter keeps track of
the ow of control between different statements in the program.
When the control returns to the calling function from the function def-
inition then the formal parameters and other variables in the function
de nition no longer contain any values.
Functions 101
Before executing the code in the source program, the Python interpreter automatically de nes
few special variables. If the Python interpreter is running the source program as a stand-alone
main program, it sets the special built-in __name__ variable to have a string value "__main__".
After setting up these special variables, the Python interpreter reads the program to execute
the code found in it. All of the code that is at indentation level 0 gets executed. Block of state-
ments in the function de nition is not executed unless the function is called.
if __name__ == "__main__":
statement(s)
The special variable, __name__ with "__main__", is the entry point to your program. When
Python interpreter reads the if statement and sees that __name__ does equal to "__main__",
it will execute the block of statements present there.
5. def main():
6. function_de nition_with_no_argument()
7. function_de nition_with_one_argument("One Argument")
8. if __name__ == "__main__":
9. main()
OUTPUT
This is a function de nition with NO Argument
This is a function de nition with One Argument
When you code Python programs, it is a best practice to put all the relevant neces-
sary calling functions inside the main() function de nition. Since the above program
is a stand-alone main source program, Python interpreter assigns the string value "__
main__" to the built-in special variable __name__ which is checked for equality using
if condition ➇–➈ and is also the entry point of your program. If the condition is True
then the Python interpreter calls the main() function. In the main() ➄ function de nition
there are two calling functions. You can have any number of function de nitions and
their calling functions in your program. When function at ➅ is called without any argu-
ments the control ows to function de nition at ➀ and displays the statement ➁. After
executing the function de nition at ➀ the control comes back to the place in the main
function from where it had left and starts executing the next statement. At this stage,
calling the function at ➆ with one argument which is a string value is executed. The
control moves over to the function de nition at ➂ which has one parameter and assigns
the string value to the message parameter. The passed string value is displayed at ➃.
102 Introduction to Python Programming
4. def main():
5. area_trapezium(10, 15, 20)
6. if __name__ == "__main__":
7. main()
OUTPUT
Area of a Trapezium is 250.0
2. def greek_mythology(god_name):
3. print(f"The God of seas according to Greek Mythology is {god_name}")
4. def main():
5. greek_mythology(god_name)
6. if __name__ == "__main__":
7. main()
OUTPUT
Who is the God of Seas according to Greek Mythology? Poseidon
The God of seas according to Greek Mythology is Poseidon
The arguments passed by the calling program and the parameters used to receive the val-
ues in the function de nition may have the same variable names. However, it is imperative
to recognize that they are entirely independent variables as they exist in different scope. In
the above code, the variable god_name appearing in the calling function ➄ and in the func-
tion de nition ➁ are different variables. The function greek_mythology() is a void function.
Functions 103
Keyword
return [expression_list]
If an expression list is present, it is evaluated, else None is substituted. The return statement
leaves the current function de nition with the expression_list (or None) as a return value.
The return statement terminates the execution of the function de nition in which it appears
and returns control to the calling function. It can also return an optional value to its calling
function.
In Python, it is possible to de ne functions without a return statement. Functions like
this are called void functions, and they return None.
If you want to return a value using return statement from the function de nition, then you
have to assign the result of the function to a variable. A function can return only a single
value, but that value can be a list or tuple.
You shall learn more about lists and tuples in Chapters 6 and 8
respectively.
104 Introduction to Python Programming
In some cases, it makes sense to return multiple values if they are related to each other. If
so, return the multiple values separated by a comma which by default is constructed as
a tuple by Python. When calling function receives a tuple from the function de nition,
it is common to assign the result to multiple variables by specifying the same number of
variables on the left-hand side of the assignment as there were returned from the function
de nition. This is called tuple unpacking.
1. def world_war():
2. alliance_world_war = input("Which alliance won World War 2?")
3. world_war_end_year = input("When did World War 2 end?")
4. return alliance_world_war, world_war_end_year
5. def main():
6. alliance, war_end_year = world_war()
7. print(f"The war was won by {alliance} and the war ended in {war_end_year}")
8. if __name__ == "__main__":
9. main()
OUTPUT
Which alliance won World War 2? Allies
When did World War 2 end? 1945
The war was won by Allies and the war ended in 1945
Line ➇ is the entry point of the program and you call the function main() ➈. In the func-
tion de nition main() you call another function world_war() ➅. The block of statements in
function de nition world_war() ➀ includes statements to get input from the user and a
return statement ➁–➃. The return statement returns multiple values separated by a comma.
Once the execution of function de nition is completed, the values from function de nition
world_war() are returned to the calling function. At the calling function on the left-hand
side of the assignment ➅ there should be matching number of variables to store the values
returned from the return statement. At ➆ returned values are displayed.
5. def calculate_sin():
Functions 105
6. result = 0
7. numerator = radians
8. denominator = 1
9. for i in range(1, nterms+1):
10. single_term = numerator / denominator
11. result = result + single_term
12. numerator = -numerator * radians * radians
13. denominator = denominator * (2 * i) * (2 * i + 1)
14. return result
OUTPUT
Enter the degrees45
Enter the number of terms5
value is sin(x) calculated using the series is 0.7071067829368671
All the trigonometric functions require their operands to be in radians. So, convert the
degrees to radians by multiplying it by π / 180 ➃. Next, a for loop ➈ is required since we
have to add and subtract each of these single_term ➉. Let us take an index i for running the
loop from 1 to nterms + 1. Let us get the rst single_term x / 1! where the variable numera-
tor represents x and the variable denominator represents 1!. Add the rst single_term to the
result which is initialized to 0 initially 11 . Now we have to get the second single_term. The
numerator for the second single_term can be obtained by multiplying −x2 to previous value of
numerator variable which was x and denominator which is 3! can be got by multiplying the
previous denominator variable by (2 * i) * (2 * i + 1) where the value of i is 1 . So, the result will
be 1 × (2 × 1) × (2 × 1 + 1) = 1 × 2 × 3 = 6. Now, you have got the second single_term which is
added to the result. Run the loop up to nterms + 1 to get the value of sin(x) which is stored in
result variable and is returned to the calculate_sin() calling function to print the result.
2. def check_armstrong_number(number):
3. result = 0
4. temp = number
5. while temp != 0:
6. last_digit = temp % 10
106 Introduction to Python Programming
7. result += pow(last_digit, 3)
8. temp = int(temp / 10)
9. if number == result:
10. print(f"Entered number {number} is a Armstrong number")
11. else:
12. print(f"Entered number {number} is not a Armstrong number")
OUTPUT
Enter a 3 digit positive number to check for Armstrong number407
Entered number 407 is a Armstrong number
A 3 digit number is called a Armstrong number if the sum of cube of its digits is equal to the
number itself. For example, 407 is an Armstrong number since 4**3 + 0**3 + 7**3 = 407. For a
number with ‘n’ digits, the power value should be n, i.e., for a 5 digit number 12345, we should
check for 1**5 + 2**5 + 3**5 + 4**5 + 5**5. Read a 3 digit positive number from the user and
store it in a variable called number ➀. Initialize the variables result and temp to zero and num-
ber respectively ➂–➃. The original number value is kept intact and the temp variable which
stores the original number is used to perform manipulations. Find the last digit of the num-
ber. To get the last digit of the number in temp variable use modulus division by 10 and assign
it to last_digit variable ➅. Find the cube of the last digit and add it to the result variable ➆. Then
remove the last digit from the number in temp variable by dividing temp by 10 and cast it as
int ➇. Repeat the logic in line ➄–➇ till the variable temp becomes 0 ➃. Finally, you will be left
with a number that is equal to the sum of the cubes of its own digits. Check the result number
against the original number to determine whether the number is Armstrong number or not.
variable has no effect on the global variable. Only the local variable has meaning inside
the function in which it is de ned.
1. test_variable = 5
2. def outer_function():
3. test_variable = 60
4. def inner_function():
5. test_variable = 100
6. print(f"Local variable value of {test_variable} having local scope to inner func-
tion is displayed")
7. inner_function()
8. print(f"Local variable value of {test_variable} having local scope to outer func-
tion is displayed ")
9. outer_function()
10. print(f"Global variable value of {test_variable} is displayed ")
OUTPUT
Local variable value of 100 having local scope to inner function is displayed
Local variable value of 60 having local scope to outer function is displayed
Global variable value of 5 is displayed
The variable name test_variable appears at different stages of the program. None of these vari-
ables are related to each other and are totally independent. In line ➀ the test_variable has global
scope and is global variable as it is available throughout the program. A test_variable is created
at line ➂ is a local variable and having scope within the outer_function() ➁. In line ➄ another
test_variable is created and is a local variable of inner_function() ➃ having local scope and it’s
life time is as far as inner_function() is executing. The change of values to test_variable in func-
tion de nitions does not have any impact on the global test_variable. The value stored in the
test_number variable is printed out as per its scope during the execution of the program ➅, ➇, ➉.
You can nest a function de nition within another function de nition. A nested func-
tion (inner function de nition) can “inherit” the arguments and variables of its outer
function de nition. In other words, the inner function contains the scope of the outer
108 Introduction to Python Programming
function. The inner function can use the arguments and variables of the outer function,
while the outer function cannot use the arguments and variables of the inner function.
The inner function de nition can be invoked by calling it from within the outer function
de nition.
5. def main():
6. result = add_cubes(2, 3)
7. print(f"The surface area after adding two Cubes is {result}")
8. if __name__ == "__main__":
9. main()
OUTPUT
The surface area after adding two Cubes is 78
The statement blocks in function de nition add_cubes(a, b) ➀ has a nested function de ni-
tion cube_surface_area(x) ➁. The outer add_cubes(a, b) function de nition has two param-
eters and inner function de nition cube_surface_area(x) has one parameter which calculates
the surface area of a cube ➂. The parameters of add_cubes(a, b) function are passed as argu-
ments to the calling function cube_surface_area(x). The inner function is called within the
outer function. The sum ➃ of the surface area of two cubes is returned ➅ and the result is
printed out ➆.
3. def main():
4. work_area("Sam works in")
5. work_area("Alice has interest in", "Internet of Things")
6. if __name__ == "__main__":
7. main()
OUTPUT
Sam works in Data Analytics
Alice has interest in Internet of Things
There are two parameters in the function header for work_area() function de nition. For the
rst parameter prompt, you have to specify the corresponding argument in the calling func-
tion. For the second parameter domain, a default value has been set ➀. In the calling function,
you may skip the second argument ➃ as it is optional. In that case, the default value set for the
parameter domain will be used in statements blocks of the function de nition ➁. If you specify
the second argument in the calling function ➄ then the default value assigned to the domain
parameter will be overwritten with the latest value as speci ed in the second argument.
5. parrot(1000)
6. parrot(voltage=1000)
7. parrot(voltage=1000000, action='VOOOOOM')
8. parrot('a thousand', state='pushing up the daisies')
OUTPUT
This parrot wouldn't voom, if you put 1000, volts through it.
Lovely plumage, the Norwegian Blue
It's a stiff !!!
This parrot wouldn't voom, if you put 1000, volts through it.
Lovely plumage, the Norwegian Blue
It's a stiff !!!
This parrot wouldn't VOOOOOM, if you put 1000000, volts through it.
Lovely plumage, the Norwegian Blue
It's a stiff !!!
This parrot wouldn't voom, if you put a thousand, volts through it.
Lovely plumage, the Norwegian Blue
It's pushing up the daisies !!!
The parrot() function de nition ➀ accepts one required parameter (voltage) and three
optional parameters (state, action, and type). In line ➄ one positional argument is speci-
ed. In line ➅, keyword argument is used to pass a value to non-optional parameter. Two
keyword arguments are speci ed in ➆ and one positional and one keyword arguments
are stated in ➇.
Also, the following functional calls are invalid.
It should be noted that the single asterisk (*) and double asterisk (**)
are the important elements here and the words args and kwargs are
used only by convention. The Python programming language does
not enforce those words and the user is free to choose any words of
his choice. Learned readers coming from C programming language
should not mistake this asterisk for a pointer.
9. def main():
10. cheese_shop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shop_keeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
OUTPUT
Do you have any Limburger ?
I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shop_keeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
The function de nition cheese_shop() has three parameters where the rst parameter
is a positional parameter and the last two parameters are *args and **kwargs ➀. In the
112 Introduction to Python Programming
statement blocks of the function de nition * and ** are not used with args and kwargs. In
the function call 10 the rst argument is assigned to the rst parameter in the function de -
nition. After the rst argument, the remaining series of arguments separated by commas
are assigned to *args until the keyword arguments are encountered. All the keyword argu-
ments in the calling function are assigned to **kwargs. You can work with **kwargs just
like you work with dictionaries. The order in which the keyword arguments are printed is
guaranteed to match the order in which they were provided in the calling function. Loops
are used to display the items in args and kwargs ➃–➇.
1. import sys
2. def main():
3. print(f"sys.argv prints all the arguments at the command line including le
name {sys.argv}")
4. print(f"len(sys.argv) prints the total number of command line arguments includ-
ing le name {len(sys.argv)}")
5. print("You can use for loop to traverse through sys.argv")
6. for arg in sys.argv:
7. print(arg)
8. if __name__ == "__main__":
9. main()
OUTPUT
C:\Introduction_To_Python_Programming\Chapter_4>python Program_4.12.py arg_1
arg_2 arg_3
sys.argv prints all the arguments at the command line including le name ['Program_4.12.
py', 'arg_1', 'arg_2', 'arg_3']
len(sys.argv) prints the total number of command line arguments including le name 4
You can use for loop to traverse through sys.argv
Program_4.12.py
arg_1
arg_2
arg_3
Functions 113
To execute a command line argument program, you need to navigate to the directory where
your program is saved. Then issue a command in the format python le_name argument_1 argu-
ment_2 argument_3 …… argument_n. Here argument_1 argument_2 and so on can be any
argument and should be separated by a space. Import sys module ➀ to access command line
arguments. Print all the arguments including le name using sys.argv ➂ but excluding the
python command. The number of arguments passed at the command line can be obtained by
len(sys.argv) ➃. A for loop can be used to traverse through each of the arguments in sys.argv ➄–➆.
4.10 Summary
• Making programs modular and reusable is one of the fundamental goals of any
programming language and functions help to achieve this goal.
• A function is a code snippet that performs some task and can be called from
another part of the code.
• There are many built-in functions provided by Python such as min(), pow() and
others and users can also create their own functions which are called as user-
de ned functions.
• A function header begins with the def keyword followed by function’s name and
parameters and ends with a colon.
• A function is called a void function if it does not return any value.
• A global variable is a variable that is de ned outside of any function de nition and a
local variable is a variable that is only accessible from within the function it resides.
• Docstrings serve the same purpose as that of comments.
• The syntax *args allows to pass a variable number of arguments to the calling function.
• The syntax **kwargs allows you to pass keyworded, variable length dictionary
arguments to the calling function.
• Command-line arguments in Python show up in sys.argv as a list of strings.
Review Questions
1. De ne function. What are the advantages of using a function?
2. Differentiate between user-de ned function and built-in functions.
3. Explain with syntax how to create a user-de ned functions and how to call the
user-de ned function from the main function.
4. Explain the built-in functions with examples in Python.
5. Differentiate between local and global variables with suitable examples.
6. Explain the advantages of *args and **kwargs with examples.
7. Demonstrate how functions return multiple values with an example.
8. Explain the utility of docstrings?
9. Write a program using functions to perform the arithmetic operations.
10. Write a program to nd the largest of three numbers using functions.
11. Write a Python program using functions to nd the value of nPr and nCr.
12. Write a Python function named area that nds the area of a pentagon.
13. Write a program using functions to display Pascal’s triangle.
14. Write a program using functions to print harmonic progression series and its sum
till N terms.
15. Write a program using functions to do the following tasks:
a. Convert milliseconds to hours, minutes and seconds.
b. Compute a sales commission, given the sales amount and the commission rate.
c. Convert Celsius to Fahrenheit.
d. Compute the monthly payment, given the loan amount, number of years and
the annual interest rate.