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

Python Unit 3 Part 1

Nice
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python Unit 3 Part 1

Nice
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

UNIT 3

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.

Advantage of Functions in Python

There are the following advantages of Python 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.

Syntax of Function(Parts of Function)

def function_name(parameters):

"""docstring"""

statement(s)

Above shown is a function definition which consists of following components.

1. Keyword def marks the start of function header.


2. A function name to uniquely identify it. Function naming follows the same rules of writing
identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of function header.

5. Optional documentation string (docstring) to describe what the function does.

6. One or more valid python statements that make up the function body. Statements must have
same indentation level (usually 4 spaces).

7. An optional return statement to return a value from the function.

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.

1. def hello_world(): #function definition


2. print("hello world")
3.
4. hello_world() #function calling

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

Call by reference in Python


In python, all the functions are called by reference, i.e., all the changes made to the reference
inside the function revert back to the original value referred by the reference.

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.

Example 1 Passing Immutable Object (List)


1. #defining the function
2. def change_list(list1):
3. list1.append(20);
4. list1.append(30);
5. print("list inside function = ",list1)
6.
7. #defining the list
8. list1 = [10,30,40,50]
9.
10. #calling the function
11. change_list(list1);
12. print("list outside function = ",list1);

Output:

list inside function = [10, 30, 40, 50, 20, 30]


list outside function = [10, 30, 40, 50, 20, 30]
Example 2 Passing Mutable Object (String)
1. #defining the function
2. def change_string (str):
3. str = str + " Hows you";
4. print("printing the string inside function :",str);
5.
6. string1 = "Hi I am there"
7.
8. #calling the function
9. change_string(string1)
10.
11. print("printing the string outside function :",string1)

Output:

printing the string inside function : Hi I am there Hows you


printing the string outside function : Hi I am there

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.

Consider the following example.

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:

Enter the name?John


Hi John

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:

Enter the principle amount? 10000


Enter the rate of interest? 5
Enter the time in years? 2
Simple Interest: 1000.0

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:

TypeError: calculate() missing 1 required positional argument: 'b'

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.

Consider the following example.

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:

printing the message with John and hello

Example 2 providing the values in different order at the calling


1. #The function simple_interest(p, t, r) is called with the keyword arguments the order of argument
s doesn't matter in this case
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4. print("Simple Interest: ",simple_interest(t=10,r=10,p=1900))

Output:

Simple Interest: 1900.0

If we provide the different name of arguments at the time of function call, an error will be
thrown.

Consider the following example.

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:

TypeError: simple_interest() got an unexpected keyword argument 'time'

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.

Consider the following example.

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:

SyntaxError: positional argument follows keyword argument

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:

My name is john and age is 22

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:

My name is john and age is 22


My name is David and age is 10

4. Variable length Arguments

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

Consider the following example.

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:

type of passed argument is <class 'tuple'>


printing the passed arguments...
john
David
smith
nick

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.

Consider the following example.

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:

hello !! I am going to print a message.


File "/root/PycharmProjects/PythonTest/Test1.py", line 5, in
print(message)
NameError: name 'message' is not defined

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

Python Built-in Functions

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:

Python abs() Function

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.

Python abs() Function Example

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

Python sum() Function

As the name says, python sum() function is used to get the sum of numbers of an iterable, i.e.,
list.

Python sum() Function Example

1. s = sum([1, 2,4 ])
2. print(s)
3.
4. s = sum([1, 2, 4], 10)
5. print(s)

Output:

7
17

Python eval() Function

The python eval() function parses the expression passed to it and runs python expression(code)
within the program.

Python eval() Function Example

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.

Python float() Example

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'

Python format() Function

The python format() function returns a formatted representation of the given value.

Python format() Function Example

1. # d, f and b are a type


2.
3. # integer
4. print(format(123, "d"))
5.
6. # float arguments
7. print(format(123.4567898, "f"))
8.
9. # binary format
10. print(format(12, "b"))

Output:

123
123.456790
1100

Python len() Function

The python len() function is used to return the length (the number of items) of an object.

Python len() Function Example

1. strA = 'Python'
2. print(len(strA))

Output:

Python id() Function

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.

Python id() Function Example

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

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.

Python sorted() Function Example

1. str = "python" # declaring string


2. # Calling function
3. sorted1 = sorted(str) # sorting string
4. # Displaying result
5. print(sorted1)

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.

Python input() Function Example

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

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.

Python int() Function Example

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

Python pow() Function

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.

Python pow() function Example

1. # positive x, positive y (x**y)


2. print(pow(4, 2))
3.
4. # negative x, positive y
5. print(pow(-4, 2))
6.
7. # positive x, negative y (x**-y)
8. print(pow(4, -2))
9.
10. # negative x, negative y
11. print(pow(-4, -2))

Output:

16
16
0.0625
0.0625

Python print() Function

The python print() function prints the given object to the screen or other standard output
devices.

Python print() function Example

1. print("Python is programming language.")


2.
3. x=7
4. # Two objects passed
5. print("x =", x)
6.
7. y=x
8. # Three objects passed
9. print('x =', x, '= y')

Output:

Python is programming language.


x=7
x=7=y

Python range() Function

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.

Python range() function Example


1. # empty range
2. print(list(range(0)))
3.
4. # using the range(stop)
5. print(list(range(4)))
6.
7. # using the range(start, stop)
8. print(list(range(1,7 )))

Output:

[]
[0, 1, 2, 3]
[1, 2, 3, 4, 5, 6]

Python round() Function

The python round() function rounds off the digits of a number and returns the floating point
number.

Python round() Function Example

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.

Python type() Function Example

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

The help() method takes maximum of one parameter.

• object (optional) - you want to generate the help of the given object

How help() works in Python?

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)

User-defined functions in Python

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.

Advantages of user-defined functions


1. User-defined functions help to decompose a large program into small segments which makes
program easy to understand, maintain and debug.
2. If repeated code occurs in a program. Function can be used to include those codes and execute
when needed by calling that function.

3. Programmars working on large project can divide the workload by making different functions.

Example of a user-defined function

# Program to illustrate
# the use of user-defined functions

def add_numbers(x,y):
sum = x + y
return sum

num1 = 5
num2 = 6

print("The sum is", add_numbers(num1, num2))

Enter a number: 2.4


Enter another number: 6.5
The sum is 8.9

You might also like