Python Unit 2
Python Unit 2
Python Unit 2
Functions
Function calls
● By using function a bigger program can be made more organized and manageable.
● The best advantage of function is that it avoids repetition and makes code reusable .
Function name(arguments)
Not all functions take an argument, and some take more than one (in which case the
arguments are separated by commas).
We have already seen an example of a function call:
>>> type("Hello,World")
<class 'str'>
>>> type(17)
<class 'int'>
The name of the function is type, and it displays the type of a value or variable. The
value or variable, which is called the argument of the function, has to be enclosed
in parentheses. It is common to say that a function “takes” an argument and
“returns” a result. The result is called the return value.
Each Python type comes with a built-in function that attempts to convert values of another
type into that type.
The int(ARGUMENT) function, for example, takes any value and converts it to an integer,
if possible, or complains otherwise:
>>> int("32")
32
>>> int("Hello")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Hello'
1
The float(ARGUMENT) function converts integers and strings to floating-point numbers:
>>> float(32)
output 32.0
>>> float("3.14159")
3.14159
The str(ARGUMENT) function converts any argument to type string:
>>> str(32)
output '32'
>>> str(3.14149)
'3.14149'
Math Functions
The math module is a standard module in python and is always available .
Eg
import math
print(math.factorial(4))
Output 24
exp(x) x
The exponential of x: e
max(x1, The largest of its arguments: the value closest to positive infinity
x2,...)
min(x1, The smallest of its arguments: the value closest to negative
x2,...) infinity
pow(x, y) The value of x**y.
2
x rounded to n digits from the decimal point. Python rounds
round(x [,n]) away from zero as a tie-breaker: round(0.5) is 1.0 and round(-
0.5) is -1.0.
abs() Method :
Description: The abs() method returns the absolute value of x i.e. the positive
distance between x and zero.
Syntax : Following is the syntax for abs()
Parameters :
x - This is a numeric expression.
Return : This method returns the absolute value of x.
The following example shows the usage of the abs() method.
>>>abs(-45)
Output : 45
Pow() method
Similarly power function takes two arguments
Syntax : pow(a,b)
>>> pow(2,3)
Output 8
Function Compositon
Usually this means that you have two or more functions where the output of one
function is the input for another . it a way of combining functions such that the result
of each function is passed as the argument of the next function.
Syntax
functionB(functionA(X))
here x is the input for functionA and the result of that is the input for functionB
Eg
import math
print(math.ceil(math.sin(45)))
Output
1
3
Adding New Functions
A new function can be created in python using keyword def followed by the
function name and arguments in parenthesis and statements to be executed in
function Example:
Defining a function:
1) First we have to use def keyword to declare the function followed by
the name of the function.
2) We can write the arguments inside the opening and closing parenthesis
() of the function if required and end declaration by colon( : )
3) Add the program statements to be executed
4) End the function with/without return statement
Syntax
def function_name(parameters):
statements
return (expression)
example :
def new_line() :
print("First Line.")
new_line()
print("Second Line")
output
First Line
Second Line
Eg 2
def myfunction():
print("Inside the function")
myfunction()
Output
Inside the function
4
Flow of Execution
● In order to ensure that a function is defined before its first use, you have to know
the order in which statements are executed, which is called the flow of execution.
● Execution always begins at the first statement of the program.
● Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the function is
called. Although it is not common, you can define one function inside another. In
this case, the inner definition isn’t executed until the outer function is called.
● It is usually not helpful to read a program from top to bottom.
● In python programs the top part of a file is almost always used for function
definitions and it is not necessary to read those until you want to understand what a
particular function does.
● The bottom part of a python file is often called the main program.
Most functions require arguments. Arguments are values that are input to the function and
these contain the data that the function works on. For example, if you want to find the
absolute value of a number (the distance of a number from zero) you have to indicate what
the number is.
>>>abs(5)
>>>abs(-5)
In this example, the arguments to the abs function are 5 and -5.
Some functions take more than one argument. For example the built-in function pow takes
two arguments, the base and the exponent. Inside the function, the values that are passed get
assigned to variables called parameters .
>>> pow(2,3)
8
>>> pow(3,2)
9
5
The first argument is raised to the power of the second argument.
Some of the functions we have used, such as the math functions, return results; they are
called fruitful functions. Other functions perform an action but don’t return a value. They
are called void functions.
● Fruitful functions tend to be very flexible—we can use the results they return to do
something else.
● For example, the fruitful isEven function can be used inside other functions any time
we need to check whether a number is even or odd as part of a larger problem.
The one on the right (using print) is a void function. Void functions are ones that don't return
anything.
● Void function tends to be less flexible—they "do something", and give us nothing
back that we can work with.
6
● For example, the void isEven function can ONLY print the word True, or print the
word False.
● We hardly ever care about "seeing the word" True or False come up on the screen,
except while we are in the testing phase of building a program—so this function is not
very useful at all.
It may not be clear why it is worth the trouble to divide a program into functions. There are
several reasons:
• Creating a new function gives you an opportunity to name a group of statements, which
makes your program easier to read and debug.
• Functions can make a program smaller by eliminating repetitive code. Later, if you make a
change, you only have to make it in one place.
• Dividing a long program into functions allows you to debug the parts one at a time and then
assemble them into a working whole.
• Well-designed functions are often useful for many programs. Once you write and debug
one, you can reuse it.
Incremental development :
As you write larger functions, you might find yourself spending more time debugging . To
deal with increasingly complex programs, you might want to try a process called
incremental development. The goal of incremental development is to avoid long debugging
sessions by adding and testing only a small amount of code at a time.
When you start out, you should add only a line or two of code at a time. As you gain more
experience, you might find yourself writing and debugging bigger chunks. Either way,
incremental development can save you a lot of debugging time.
1. Start with a working program and make small incremental changes. At any point, if
there is an error, you should have a good idea where it is.
2. Use temporary variables to hold intermediate values so you can display and check
them.
3. Once the program is working, you might want to remove some of the scaffolding or
consolidate multiple statements into compound expressions, but only if it does not
make the program difficult to read.
7
Boolean functions :
Functions can return Booleans, which is often convenient for hiding complicated tests inside
functions. The result of Boolean function is always either True or False .The result can be
assigned to Boolean variable . On the basis of the value of boolean function result we can
decide the further code execution .
For example:
def is_divisible(x, y):
if x % y == 0:
return True
else:
return False
print(is_divisible(6, 4))
print(is_divisible(6, 3))
output
False
True
8
It is common to give Boolean functions names that sound like yes/no
questions; is_divisible returns either True or False to indicate whether x is divisible by y.
Recursion :
Example:
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1
Replacing the calculated values gives us the following expression
4! = 4 * 3 * 2 * 1
Eg:
def factorial(n):
if n == 1:
return 1
else:
res = n * factorial(n-1)
return res
print(factorial(5))
o/p
120
Checking Types
The built-in function isinstance is introduced in this section. The function verifies the type of
argument
Syntax
isintance(object,classinfo)
Where
object : an object instance
classinfo : a class
9
Eg
>>>isinstance(‘a’,int)
False
CHAPTER 5
STRINGS
>>> fruit='banana'
>>> print(fruit[1])
Output
a
>>> print(fruit[4])
Index can be of two types viz : forward index and backward index
FORWARD INDEX :
0 1 2 3 4
H E L L O
BACKWARD INDEX
-5 -4 -3 -2 -1
So
>>> print(fruit[-4])
10
Traversal with a for loop
st="hello"
i=0
for i in st:
print(i)
output:
String slices
Syntax:
S[start:end]
This will return part of the string starting from index start to (index end -1)
11
Strings are immutable
Strings are immutable which means you can’t change an existing string. The best you can do
is create a new string that is a variation on the original:
This example concatenates a new first letter onto a slice of greeting. It has no effect on the
original string.
Searching :
It is the process of checking occurrence of substring in whole string or in a substring finding the
occurrence of character string if starting index beg and ending index end are given
Syntax
12
String methods :
st=" College"
print(st)
print(st.swapcase())
print(st.lower())
print(st.upper())
print(len(st))
print(st.capitalize())
output
College
cOLLEGE
college
COLLEGE
7
College
13
The in and not in operator :
The word in is a Boolean operator that takes two strings and returns True if the first appears
as a substring in the second:
>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False
14