Python Unit 3 Part 1
Python Unit 3 Part 1
Python Functions
In Python, function is a group of related statements that perform a specific task.
Functions are the most important aspect of an application. A function can be defined as the
organized block of reusable code which can be called whenever required.
Python allows us to divide a large program into the basic building blocks known as function. The
function contains the set of programming statements. A function can be called multiple times to
provide reusability and modularity to the python program.
In other words, we can say that the collection of functions creates a program. The function is also
known as procedure or subroutine in other programming languages.
Python provide us various inbuilt functions like range() or print(). Although, the user can create
its functions which can be called user-defined functions.
o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call python functions any number of times in a program and from any place in a
program.
o We can track a large python program easily when it is divided into multiple functions.
o Reusability is the main achievement of python functions.
o However, Function calling is always overhead in a python program.
def function_name(parameters):
"""docstring"""
statement(s)
6. One or more valid python statements that make up the function body. Statements must have
same indentation level (usually 4 spaces).
Function calling
In python, a function must be defined before the function calling otherwise the python interpreter
gives an error. Once the function is defined, we can call it from another function or the python
prompt. To call the function, use the function name followed by the parentheses.
A simple function that prints the message "Hello Word" is given below.
Output:
hello world
Parameters in function
The information into the functions can be passed as the parameters. The parameters are specified
in the parentheses. We can give any number of parameters, but we have to separate them with a
comma.
Consider the following example which contains a function that accepts a string as the parameter
and prints it.
Example 1
1. #defining the function
2. def func (name):
3. print("Hi ",name);
4.
5. #calling the function
6. func("Ayush")
Example 2
1. #python function to calculate the sum of two variables
2. #defining the function
3. def sum (a,b):
4. return a+b;
5.
6. #taking values from the user
7. a = int(input("Enter a: "))
8. b = int(input("Enter b: "))
9.
10. #printing the sum of a and b
11. print("Sum = ",sum(a,b))
Output:
Enter a: 10
Enter b: 20
Sum = 30
However, there is an exception in the case of mutable objects since the changes made to the
mutable objects like string do not revert to the original string rather, a new string object is made,
and therefore the two different objects are printed.
Output:
Output:
Types of arguments
There may be several types of arguments which can be passed at the time of function calling.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1. Required Arguments
These are the arguments which are required to be passed at the time of function calling with the
exact match of their positions in the function call and function definition. If either of the
arguments is not provided in the function call, or the position of the arguments is changed, then
the python interpreter will show the error.
Example 1
1. #the argument name is the required argument to the function func
2. def func(name):
3. message = "Hi "+name;
4. return message;
5. name = input("Enter the name?")
6. print(func(name))
Output:
Example 2
1. #the function simple_interest accepts three arguments and returns the simple interest accordingly
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4. p = float(input("Enter the principle amount? "))
5. r = float(input("Enter the rate of interest? "))
6. t = float(input("Enter the time in years? "))
7. print("Simple Interest: ",simple_interest(p,r,t))
Output:
Example 3
1. #the function calculate returns the sum of two arguments a and b
2. def calculate(a,b):
3. return a+b
4. calculate(10) # this causes an error as we are missing a required arguments b.
Output:
2. Keyword arguments
Python allows us to call the function with the keyword arguments. This kind of function call will
enable us to pass the arguments in the random order.
The name of the arguments is treated as the keywords and matched in the function calling and
definition. If the same match is found, the values of the arguments are copied in the function
definition.
Example 1
1. #function func is called with the name and message as the keyword arguments
2. def func(name,message):
3. print("printing the message with",name,"and ",message)
4. func(name = "John",message="hello") #name and message is copied with the values John and he
llo respectively
Output:
Output:
If we provide the different name of arguments at the time of function call, an error will be
thrown.
Example 3
1. #The function simple_interest(p, t, r) is called with the keyword arguments.
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4.
5. print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900)) # doesn't find the ex
act match of the name of the arguments (keywords)
Output:
The python allows us to provide the mix of the required arguments and keyword arguments at
the time of function call. However, the required argument must not be given after the keyword
argument, i.e., once the keyword argument is encountered in the function call, the following
arguments must also be the keyword arguments.
Example 4
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. func("John",message="hello",name2="David") #the first argument is not the keyword argument
Output:
printing the message with John , hello ,and David
The following example will cause an error due to an in-proper mix of keyword and required
arguments being passed in the function call.
Example 5
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. func("John",message="hello","David")
Output:
3. Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of any of the
argument is not provided at the time of function call, then that argument can be initialized with
the value given in the definition even if the argument is not specified at the function call.
Example 1
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however the default val
ue of age is considered in the function
Output:
Example 2
3. def printme(name,age=22):
3. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however the default val
ue of age is considered in the function
3. printme(age = 10,name="David") #the value of age is overwritten here, 10 will be printed as age
Output:
In the large projects, sometimes we may not know the number of arguments to be passed in
advance. In such cases, Python provides us the flexibility to provide the comma separated values
which are internally treated as tuples at the function call.
However, at the function definition, we have to define the variable with * (star) as *<variable -
name >.
Example
1. def printme(*names):
2. print("type of passed argument is ",type(names))
3. print("printing the passed arguments...")
4. for name in names:
5. print(name)
6. printme("john","David","smith","nick")
Output:
Scope of variables
The scopes of the variables depend upon the location where the variable is being declared. The
variable declared in one part of the program may not be accessible to the other parts.
In python, the variables are defined with the two types of scopes.
1. Global variables
2. Local variables
The variable defined outside any function is known to have a global scope whereas the variable
defined inside a function is known to have a local scope.
Example 1
1. def print_message():
2. message = "hello !! I am going to print a message." # the variable message is local to the funct
ion itself
3. print(message)
4. print_message()
5. print(message) # this will cause an error since a local variable cannot be accessible here.
Output:
Example 2
1. def calculate(*args):
2. sum=0
3. for arg in args:
4. sum = sum +arg
5. print("The sum is",sum)
6. sum=0
7. calculate(10,20,30) #60 will be printed as the sum
8. print("Value of sum outside the function:",sum) # 0 will be printed
Output:
The sum is 60
Value of sum outside the function: 0
The Python built-in functions are defined as the functions whose functionality is pre-defined in
Python. The python interpreter has several functions that are always present for use. These
functions are known as Built-in Functions. There are several built-in functions in Python which
are listed below:
The python abs() function is used to return the absolute value of a number. It takes only one
argument, a number whose absolute value is to be returned. The argument can be an integer and
floating-point number. If the argument is a complex number, then, abs() returns its magnitude.
1. # integer number
2. integer = -20
3. print('Absolute value of -40 is:', abs(integer))
4.
5. # floating number
6. floating = -20.83
7. print('Absolute value of -40.83 is:', abs(floating))
Output:
Absolute value of -20 is: 20
Absolute value of -20.83 is: 20.83
As the name says, python sum() function is used to get the sum of numbers of an iterable, i.e.,
list.
1. s = sum([1, 2,4 ])
2. print(s)
3.
4. s = sum([1, 2, 4], 10)
5. print(s)
Output:
7
17
The python eval() function parses the expression passed to it and runs python expression(code)
within the program.
1. x = 8
2. print(eval('x + 1'))
Output:
Python float()
The python float() function returns a floating-point number from a number or string.
1. # for integers
2. print(float(9))
3.
4. # for floats
5. print(float(8.19))
6.
7. # for string floats
8. print(float("-24.27"))
9.
10. # for string floats with whitespaces
11. print(float(" -17.19\n"))
12.
13. # string float error
14. print(float("xyz"))
Output:
9.0
8.19
-24.27
-17.19
ValueError: could not convert string to float: 'xyz'
The python format() function returns a formatted representation of the given value.
Output:
123
123.456790
1100
The python len() function is used to return the length (the number of items) of an object.
1. strA = 'Python'
2. print(len(strA))
Output:
Python id() function returns the identity of an object. This is an integer which is guaranteed to be
unique. This function takes an argument as an object and returns a unique integer number which
represents identity. Two objects with non-overlapping lifetimes may have the same id() value.
1. # Calling function
2. val = id("Javatpoint") # string object
3. val2 = id(1200) # integer object
4. val3 = id([25,336,95,236,92,3225]) # List object
5. # Displaying result
6. print(val)
7. print(val2)
8. print(val3)
Output:
139963782059696
139963805666864
139963781994504
Python sorted() function is used to sort elements. By default, it sorts elements in an ascending
order but can be sorted in descending also. It takes four arguments and returns a collection in
sorted order. In the case of a dictionary, it sorts only keys, not values.
Output:
[‘h’,’n’,’o’,’p’,’p’,’y’]
Python input() Function
Python input() function is used to get an input from the user. It prompts for the user input and
reads a line. After reading data, it converts it into a string and returns it. It throws an
error EOFError if EOF is read.
1. # Calling function
2. val = input("Enter a value: ")
3. # Displaying result
4. print("You entered:",val)
Output:
Enter a value: 45
You entered: 45
Python int() function is used to get an integer value. It returns an expression converted into an
integer number. If the argument is a floating-point, the conversion truncates the number. If the
argument is outside the integer range, then it converts the number into a long type.
If the number is not a number or if a base is given, the number must be a string.
1. # Calling function
2. val = int(10) # integer value
3. val2 = int(10.52) # float value
4. val3 = int('10') # string value
5. # Displaying result
6. print("integer values :",val, val2, val3)
Output:
integer values : 10 10 10
The python pow() function is used to compute the power of a number. It returns x to the power
of y. If the third argument(z) is given, it returns x to the power of y modulus z, i.e. (x, y) % z.
Output:
16
16
0.0625
0.0625
The python print() function prints the given object to the screen or other standard output
devices.
Output:
The python range() function returns an immutable sequence of numbers starting from 0 by
default, increments by 1 (by default) and ends at a specified number.
Output:
[]
[0, 1, 2, 3]
[1, 2, 3, 4, 5, 6]
The python round() function rounds off the digits of a number and returns the floating point
number.
1. # for integers
2. print(round(10))
3.
4. # for floating point
5. print(round(10.8))
6.
7. # even choice
8. print(round(6.6))
Output:
10
11
7
Python type()
The python type() returns the type of the specified object if a single argument is passed to the
type() built in function. If three arguments are passed, then it returns a new type object.
1. List = [4, 5]
2. print(type(List))
3.
4. Dict = {4: 'four', 5: 'five'}
5. print(type(Dict))
6.
7. class Python:
8. a=0
9.
10. InstanceOfPython = Python()
11. print(type(InstanceOfPython))
Output:
<class 'list'>
<class 'dict'>
<class '__main__.Python'>
help() Parameters
• object (optional) - you want to generate the help of the given object
The help() method is used for interactive use. It's recommenced to try it in your interpreter when
you need help to write Python program.
object is passed to help() (not a string)
Functions that we define ourselves to do certain specific task are referred as user-defined
functions. The way in which we define and call functions in Python are already discussed.
Functions that readily come with Python are called built-in functions. If we use functions written
by others in the form of library, it can be termed as library functions.
All the other functions that we write on our own fall under user-defined functions. So, our user-
defined function could be a library function to someone else.
3. Programmars working on large project can divide the workload by making different functions.
# Program to illustrate
# the use of user-defined functions
def add_numbers(x,y):
sum = x + y
return sum
num1 = 5
num2 = 6