Unit 3
Unit 3
UNIT-III
Functions: Function Definition – Function Call – Variable Scope and its Lifetime-Return
Statement.Function Arguments:Required Arguments,Keyword Arguments, Default
Arguments and Variable Length Arguments-Recursion.Python Strings:String operations-
Immutable Strings - Built-in String Methods and Functions - String Comparison.Modules:
import statement- The Python module – dir() function – Modules and Namespace–
Defining our own modules.
Function
The Python provides several functions and methods to write code very easily, and these
functions and methods are called built-in function and methods. Python allows us to create
our functions and methods, and these are called user-defined functions and methods.
This gives us access to all the functions in the module(s). To call a function of a
module, the function name should be preceded with the name of the module with
a dot(.) as a separator.
The syntax is as shown below:
modulename.functionname()
Built-in Modules
Python library has many built-in modules that are really handy to programmers. Some
commonly used modules and the frequently used functions that are found in those
modules:
• math
• random
• statistics
math module:
It contains different types of mathematical functions. In order to
use the math module we need to import it using the following statement:
import math
random module:
This module contains functions that are used for generating random numbers. In order
to use the random module we need to import it using the following statement:
import random
statistics module:
This module provides functions for calculating statistics of numeric (Real-valued) data. In
order to use the statistics module we need to import it using the following
statement:
import statistics
Commonly used functions in statistics module
Function Syntax Returns Example Output
>>> statistics.
mean([11,24,32,45,51])
statistics.mean(x) arithmetic mean
32.6
>>>statistics.
median (middle median([11,24,32,45,51])
statistics.median(x)
value) of x
32
>>> statistics.
mode([11,24,11,45,11])
11
mode (the most
statistics.mode(x)
repeated value) >>> statistics.
mode(("red","blue","red"))
'red'
• In order to get a list of modules available in Python, we can use the following
statement:
>>> help("module")
• To view the content of a module say math, type the following:
>>> help("math")
From Statement
Instead of loading all the functions into memory by importing a module, from statement
can be used to access only the required functions from a module. It loads only the specified
function(s) instead of all the functions in a module.
Syntax :
>>> from modulename import functionname
Example :
Function Definition and Calling the Function / User-defined Functions
The Python programming language provides the keyword def to create functions. The
general syntax to create functions is as follows.
Syntax
def function_name(list_of_parameters):
statement_1
statement_2
statement_3
...
In Python, we use the name of the function to make a function call. If the function requires
any parameters, we need to pass them while calling it.
The general syntax for calling a function is as follows.
Syntax
function_name(parameter_1, parameter_2,...)
display()
When we run the above example code, it produces the following output.
Write a user defined function to add 2 numbers and display their sum.
#function definition
def addnum():
fnum = int(input("Enter first number: "))
snum = int(input("Enter second number: "))
sum = fnum + snum
print("The sum of ",fnum,"and ",snum,"is ",sum)
#function call
addnum()
When we run the above example code, it produces the following output.
WAP using a user defined function that displays sum of first n natural
numbers, where n is passed as an argument.
#function definition
def sumSquares(n):
sum = 0
for i in range(1,n+1):
sum = sum+i
print("The sum of first",n,"natural numbers is: ",sum)
def calcFact(num):
fact = 1
for i in range(num,0,-1):
fact = fact * i
print("Factorial of",num,"is",fact)
When we run the above example code, it produces the following output.
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
def area_trapezium(a,b,h):
area=0.5*(a+b)*h
print("Area of a Trapezium is ",area)
def main():
area_trapezium(10,15,20)
if name == " main ":
main()
When we run the above example code, it produces the following output
A function may or may not return a value when called. The return statement returns
the values from the function.
A return statement consists of the return keyword followed by an
optional return value.
print(add(2, 2))
Output : 4
Armstrong Number : The sum of cubes of each digit is equal to the number itself.
For example:
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.
When we run the above example code, it produces the following output
num1 = 5 #globalvariable
def myfunc():
# variable num1 outside the function
print("Accessing num =",num1)
num = 10 #localvariable
print("num reassigned =", num)
myfunc()
print("Accessing num outside myfunc",num1)
When we run the above example code, it produces the following output
Calculate and Add the Surface Area of Two Cubes. Use Nested Functions
def main():
result=add_cubes(2, 3)
print("The surface area after adding two Cubes
is",result)
When we run the above example code, it produces the following output
Keyword Arguments
The keyword argument is an argument passed as a value along with the parameter name
(kwarg = value).
When keyword arguments are used, we may ignore the order of arguments. We may pass
the arguments in any order because the Python interpreter uses the keyword provided to
match with the respective parameter.
def largest(*numbers):
return max(numbers)
print(largest(20, 35))
print(largest(2, 5, 3))
print(largest(10, 40, 80, 50))
print(largest(16, 3, 9, 12, 44, 40))
When we run the above example code, it produces the following output
Python has **kwargs which allows us to pass the variable length of keyword arguments
to the function. In the function, we use the double-asterisk (**) before the parameter
name to denote this type of argument.
Example program on **kwargs
def Student_info(**kwargs):
print(kwargs)
Student_info(name="Raju",rollno=111,group="MSDs")
When we run the above example code, it produces the following output
import sys
print("Number of arguments:",len(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)
Python allows an index value to be negative also. Negative indices are used when
we want to access the characters of the string from right to left.
Starting from right hand side, the first character has the index as -1 and the last
character has the index –n where n is the length of the string.
String is Immutable
A string is an immutable data type. It means that the contents of the string cannot be
changed after it has been created. An attempt to do this would lead to an error.
STRING OPERATIONS
Python allows certain operations on string data type, such as concatenation, repetition,
membership and slicing.
Concatenation
To concatenate means to join. Python allows us to join two strings using concatenation
operator plus which is denoted by symbol +.
Repetition
Python allows us to repeat the given string using repetition operator which is denoted by
symbol *
Note: str1 still remains the same after the use of repetition operator
Membership
Python has two membership operators 'in' and 'not in'. The 'in' operator takes
two strings and returns True if the first string appears as a substring in the second string,
otherwise it returns False.
The 'not in' operator also takes two strings and returns True if the first string does
not appear as a substring in the second string, otherwise returns False.
Slicing
In Python, to access some part of a string or substring, we use a method called slicing. This
can be done by specifying an index range.
To access substring from a string, we use string variable name followed by square brackets
with starting index , ending index and Step of the required substring.
#first index > second index results in an #empty '' string
If the first index is not mentioned, the slice starts from index and If the second index is not
mentioned, the slicing is done till the length of the string.
The slice operation can also take a third index that specifies the ‘step size’. For
example, str1[n:m:k], means every kth character has to be extracted from the string
str1 starting from n and ending at m-1. By default, the step size is one.
Negative indexes can also be used for slicing. If we ignore both the indexes and give step
size as -1 , str1 string is obtained in the reverse order.
Joining
The join() string method returns a string by joining all the elements of an iterable (list,
string, tuple), separated by a string separator.
Traversing A String
We can access each character of a string or traverse a string using for loop and
while loop
String Traversal Using for Loop:
Write Python Program to Convert Uppercase Letters to Lowercase and Vice Versa
def case_conversion(string):
str1=str()
for ch in string:
if ch.isupper():
str1+=ch.lower()
else:
str1 += ch.upper()
print("The modified string is ",str1)
def main():
str2=input("Enter a String :")
case_conversion(str2)
if name ==" main ":
main()
Output :
Enter a String : Hello WORLD
The modified string is hELLO world
Example Program on String Methods
Output :
String in Uppercase : HELLO WORLD!
String in Lower case : hello world!
Capitalized String : hello world!
String with first letter : Hello World!
String alphanumeric : False
String in lowercase : False
String in uppercase : False
Swapcase : HELLO wORLD!
Right Strip of String : hello World!
Left Strip of String : hello World!
Right & Left Strip of String : hello World!
Formatting Strings
Python f-string is the newest Python syntax to do string formatting. It is available since
Python 3.6. Python f-strings provide a faster, more readable, more concise, and less error
prone way of formatting strings in Python.
The f-strings have the f prefix and use {} brackets to evaluate values.
The format strings will contain the curly braces { } and the format() method will use those
curly braces { } as placeholders to replace with the content of the parameters.
name = 'Raju'
age = 23
print('%s is %d years old' % (name, age))
print('{} is {} years old'.format(name, age))
print(f'{name} is {age} years old')
Output :
Raju is 23 years old
Raju is 23 years old
Raju is 23 years old
Function Prototypes:
Based on the data flow between the calling function and called function, the functions
are classified as follows...
Function without Parameters and without Return value
Function with Parameters and without Return value
Function without Parameters and with Return value
Function with Parameters and with Return value
In this type of functions there is data transfer from calling-function to called function
(parameters) but there is no data transfer from called function to calling-function
(return value).
The execution control jumps from calling-function to called function along with the
parameters and executes called function, and finally comes back to the calling
function.
def add():
a = int(input("enter a"))
b = int(input("enter b"))
c = a + b Output :
return c enter a 10
enter b 20
c = add() 30
print(c)
def add(a,b):
c = a + b Output :
return c enter a 10
a = int(input("enter a")) enter b 20
b = int(input("enter b")) 30
c = add(a,b)
print(c)
Unit-III Questions
1. Explain 4 different function prototypes with an example programs
2. Explain built in functions with suitable examples
3. Write a short note on return statement in function with an example
program.
4. Explain Commonly used modules with an example programs
5. Write a short note on formatted strings
6. Explain built-in functions with examples
7. Differentiate between local and global variables with suitable examples
8. Define Function. Explain with syntax how to create a used-defined functions
and how to call the user -defined functions / how to call user defined functions
from the main function
9. Explain about default arguments , *args and **kwargs
10. Write a short note on Command line arguments with an example program
11. Explain strings in detail (Creating and accessing )
12. Explain string operations in detail.
Explain string methods with an