0% found this document useful (0 votes)
78 views

Amat111 CH 4 Functions

The document discusses functions in Python programming. It defines functions as reusable blocks of code that perform tasks. Built-in functions like abs(), min(), max() are included in Python, while user-defined functions can be created. Functions reduce program size and allow code re-use. Modules contain groups of functions and are imported using import statements. Commonly used modules like math and random are demonstrated.

Uploaded by

Adrian Daniel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

Amat111 CH 4 Functions

The document discusses functions in Python programming. It defines functions as reusable blocks of code that perform tasks. Built-in functions like abs(), min(), max() are included in Python, while user-defined functions can be created. Functions reduce program size and allow code re-use. Modules contain groups of functions and are imported using import statements. Commonly used modules like math and random are demonstrated.

Uploaded by

Adrian Daniel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

4

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

• Understand the purpose of functions in Python.


• De ne and invoke functions.
• Receive the returned data from functions.
• Understand the use of modules and built-in functions in Python.
• Determine the scope of variables.
• Recognize different forms of function arguments.

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.

4.1 Built-In Functions


The Python interpreter has a number of functions that are built into it and are always
available. You have already looked at some of the built-in functions like input(), print(), range()
and others in previous chapters. Let’s discuss few more built-in functions (TABLE 4.1).

95
96 Introduction to Python Programming

TABLE 4.1
A Few Built-in Functions in Python
Function Name Syntax Explanation

abs() abs(x) The abs() function returns the absolute value of a


where x is an integer or number.
oating-point number.
min() min(arg_1, arg_2, arg_3,…, The min() function returns the smallest of two or
arg_n) more arguments.
where arg_1, arg_2, arg_3 are
the arguments.
max() max(arg_1, arg_2, arg_3,…,arg_n) The max() function returns the largest of two or
where arg_1, arg_2, arg_3 are more arguments.
the arguments.
divmod() divmod(a, b) The divmod() function takes two numbers as
where a and b are numbers arguments and return a pair of numbers
representing numerator and consisting of their quotient and remainder. For
denominator. example, if a and b are integer values, then the
result is the same as (a // b, a % b). If either a or b
is a oating-point number, then the result is (q, a
% b), where q is the whole number of the quotient.
pow() pow(x, y) The pow(x, y) function returns x to the power y
where x and y are numbers. which is equivalent to using the power operator:
x**y.
len() len(s) The len() function returns the length or the number
where s may be a string, byte, of items in an object.
list, tuple, range, dictionary or
a set.

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

Demonstration of various built-in functions ➀–➆.


Functions 97

4.2 Commonly Used Modules


Modules in Python are reusable libraries of code having .py extension, which implements
a group of methods and statements. Python comes with many built-in modules as part of
the standard library.
To use a module in your program, import the module using import statement. All the
import statements are placed at the beginning of the program.
The syntax for import statement is,

Keyword
import module_name

For example, you can import the math module as

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()

The module name and function name are separated by a dot.

Here we list some of the functions supported by math module.

1. >>> import math


2. >>> print(math.ceil(5.4))
6
3. >>> print(math.sqrt(4))
2.0
4. >>> print(math.pi)
3.141592653589793
5. >>> print(math.cos(1))
0.5403023058681398
6. >>> math.factorial(6)
720
7. >>> math.pow(2, 3)
8.0

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']

Various functions associated with math module is displayed ➀


Another built-in function you will nd useful is the help() function which invokes the
built-in help system. The argument to the help() function is a string, which is looked up as the
name of a module, function, class, method, keyword, or documentation topic, and then a related
help page is printed in the console. For example, if you want to nd information about gcd()
function in math module then pass the function name as an argument without parenthesis.

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

Help page related to math.gcd is printed in the console ➀.

Another useful module in the Python standard library is the random module which gen-
erates random numbers.

1. >>> import random


2. >>> print(random.random())
0.2551941897892144
3. >>> print(random.randint(5,10))
9

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,

pip install module_name


Functions 99

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.

1. C:\> pip install arrow

Install arrow module using pip command ➀.


Below code shows a simple usage of arrow module.

1. >>> import arrow


2. >>> a = arrow.utcnow()
3. >>> a.now()
<Arrow [2017-12-23T20:45:14.490380+05:30]>

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 ➂.

4.3 Function Definition and Calling the Function


You can create your own functions and use them as and where it is needed. User-de ned
functions are reusable code blocks created by users to perform some speci c task in the
program.
The syntax for function de nition is,

User defined Parameters


Keyword
def function_name(parameter_1, parameter_2, …, parameter_n):

Indentation statement(s)
Colon should be present at
the end

In Python, a function de nition consists of the def keyword, followed by

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.

Program 4.1: Program to Demonstrate a Function with and without Arguments

1. def function_de nition_with_no_argument():


2. print("This is a function de nition with NO Argument")

3. def function_de nition_with_one_argument(message):


4. print(f"This is a function de nition with {message}")

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

Program 4.2: Program to Find the Area of Trapezium Using the Formula


Area = (1/2) * (a + b) * h Where a and b Are the 2 Bases
of Trapezium and h Is the Height

1. def area_trapezium(a, b, h):


2. area = 0.5 * (a + b) * h
3. print(f"Area of a Trapezium is {area}")

4. def main():
5. area_trapezium(10, 15, 20)

6. if __name__ == "__main__":
7. main()

OUTPUT
Area of a Trapezium is 250.0

Here the function de nition area_trapezium(a, b, h) uses three formal parameters a, b, h ➀


to stand for the actual values passed by the user in the calling function area_trapezium(10,
15, 20) ➄. The arguments in the calling function are numbers. The variables a, b and h are
assigned with values of 10, 15 and 20 respectively. The area of a trapezium is calculated
using the formula 0.5 * (a + b) * h and the result is assigned to the variable area ➁ and the
same is displayed ➂.

Program 4.3: Program to Demonstrate Using the Same Variable Name


in Calling Function and Function De nition

1. god_name = input("Who is the God of Seas according to Greek Mythology?")

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

Scope refers to the visibility of variables. In other words, which parts


of your program can see or use it.

4.4 The return Statement and void Function


Most of the times you may want the function to perform its speci ed task to calculate a value
and return the value to the calling function so that it can be stored in a variable and used
later. This can be achieved using the optional return statement in the function de nition.
The syntax for return statement is,

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.

Functions without a return statement do return a value, albeit a rather


boring one. This value is called None (it is a built-in name) which stands
for “nothing”. Writing the value None is normally suppressed by the
interpreter if it would be the only value written.

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.

Program 4.4: Program to Demonstrate the Return of Multiple Values from a


Function De nition

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.

Program 4.5: Calculate the Value of sin(x) up to n Terms Using the Series


x x 3 x 5 x7
sin ( x ) = − + − + Where x Is in Degrees
1! 3! 5! 7!
1. import math
2. degrees = int(input("Enter the degrees"))
3. nterms = int(input("Enter the number of terms"))
4. radians = degrees * math.pi / 180

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

15. def main():


16. result = calculate_sin()
17. print(f"value is sin(x) calculated using the series is {result} ")

18. if __name__ == "__main__":


19. main()

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.

Program 4.6: Program to Check If a 3 Digit Number Is Armstrong Number or Not

1. user_number = int(input("Enter a 3 digit positive number to check for Armstrong


number"))

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")

13. def main():


14. check_armstrong_number(user_number)

15. if __name__ == "__main__":


16. main()

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.

4.5 Scope and Lifetime of Variables


Python programs have two scopes: global and local. A variable is a global variable if its
value is accessible and modi able throughout your program. Global variables have a
global scope. A variable that is de ned inside a function de nition is a local variable. The
lifetime of a variable refers to the duration of its existence. The local variable is created and
destroyed every time the function is executed, and it cannot be accessed by any code out-
side the function de nition. Local variables inside a function de nition have local scope
and exist as long as the function is executing.
It is possible to access global variables from inside a function, as long as you have not
de ned a local variable with the same name. A local variable can have the same name
as a global variable, but they are totally different so changing the value of the local
Functions 107

variable has no effect on the global variable. Only the local variable has meaning inside
the function in which it is de ned.

Program 4.7: Program to Demonstrate the Scope of Variables

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 ➅, ➇, ➉.

It is not recommended to access global variables from inside the


de nition of the function. If there is a need by function to access
an external value then it should be passed as a parameter to that
function.

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.

Program 4.8: Calculate and Add the Surface Area of Two Cubes.


Use Nested Functions

1. def add_cubes(a, b):


2. def cube_surface_area(x):
3. return 6 * pow(x, 2)
4. return cube_surface_area(a) + cube_surface_area(b)

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 ➆.

4.6 Default Parameters


In some situations, it might be useful to set a default value to the parameters of the func-
tion de nition. This is where default parameters can help. Each default parameter has a
default value as part of its function de nition. Any calling function must provide argu-
ments for all required parameters in the function de nition but can omit arguments for
default parameters. If no argument is sent for that parameter, the default value is used.
Usually, the default parameters are de ned at the end of the parameter list, after any
required parameters and non-default parameters cannot follow default parameters. The
default value is evaluated only once.
Functions 109

Program 4.9: Program to Demonstrate the Use of Default Parameters

1. def work_area(prompt, domain="Data Analytics"):


2. print(f"{prompt} {domain}")

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.

4.7 Keyword Arguments


Until now you have seen that whenever you call a function with some values as its argu-
ments, these values get assigned to the parameters in the function de nition according to
their position. In the calling function, you can explicitly specify the argument name along
with their value in the form kwarg = value. In the calling function, keyword arguments
must follow positional arguments. All the keyword arguments passed must match one of
the parameters in the function de nition and their order is not important. No parameter
in the function de nition may receive a value more than once.

Program 4.10: Program to Demonstrate the Use of Keyword Arguments

1. def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):


2. print(f"This parrot wouldn't {action}, if you put {voltage}, volts through it.")
3. print(f"Lovely plumage, the {type}")
4. print(f"It's {state} !!!")
110 Introduction to Python Programming

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.

parrot() # required argument missing


parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument
parrot(110, voltage=220) # duplicate value for the same argument
parrot(actor='John Cleese') # unknown keyword argument

4.8 *args and **kwargs


*args and **kwargs are mostly used as parameters in function de nitions. *args and
**kwargs allows you to pass a variable number of arguments to the calling function. Here
variable number of arguments means that the user does not know in advance about how
many arguments will be passed to the calling function. *args as parameter in function de -
nition allows you to pass a non-keyworded, variable length tuple argument list to the call-
ing function. **kwargs as parameter in function de nition allows you to pass keyworded,
variable length dictionary argument list to the calling function. *args must come after all
the positional parameters and **kwargs must come right at the end.
Functions 111

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.

Program 4.11: Program to Demonstrate the Use of *args and **kwargs

1. def cheese_shop(kind, *args, **kwargs):


2. print(f"Do you have any {kind} ?")
3. print(f"I'm sorry, we're all out of {kind}")
4. for arg in args:
5. print(arg)
6. print("-" * 40)
7. for kw in kwargs:
8. print(kw, ":", kwargs[kw])

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")

11. if __name__ == "__main__":


12. main()

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 ➃–➇.

4.9 Command Line Arguments


A Python program can accept any number of arguments from the command line.
Command line arguments is a methodology in which user will give inputs to the program
through the console using commands. You need to import sys module to access command
line arguments. All the command line arguments in Python can be printed as a list of
string by executing sys.argv.

Program 4.12: Program to Demonstrate Command Line Arguments in Python

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.

Multiple Choice Questions


1. A local variable in Python is a variable that is,
a. De ned inside every function
b. Local to the given program
c. Accessible from within the function
d. All of these
2. Which of the following statements are the advantages of using functions?
a. Reduce duplication of code
b. Clarity of code
c. Reuse of code
d. All of these
Functions 117

22. Gauge the output of the following code.


def foo():
return total + 1
total = 0
print(foo())
a. 1
b. 0
c. 11
d. 00
23. The default arguments speci ed in the function header is an
a. Identi er followed by an = and the default value
b. Identi er followed by the default value within back-ticks
c. Identi er followed by the default value within []
d. Identi er followed by an #.

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.

You might also like