Python Unit 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

UNIT 2 : FUNCTIONS AND STRINGS

Functions
Function calls

● A function is a block of organised , reusable code that is used to perform a


single ,related action.
● Functions help break our program into smaller and modular code blocks .

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

The syntax of a function call is simply

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.

Type Conversion Functions :

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

Function Returns ( description )

abs(x) The absolute value of x: the (positive) distance between x and


zero.
ceil(x) The ceiling of x: the smallest integer not less than x

exp(x) x
The exponential of x: e

floor(x) The floor of x: the largest integer not greater than x

log(x) The natural logarithm of x, for x> 0

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.

● Statements are executed one at a time, in order from top to bottom.

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

● This part can be recognized because it is often not indented.

● It is easier to understand a the program by following flow of execution starting at


the beginning of the main program

Parameters and Arguments

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.

Program to find maximum number among two numbers

def fnmax(s,t) #s and t are parameter , general placeholder


if s>t :
print (s,” is maximum”)
elif s==t
print(S,”is equal to t”)
else:
print(t,”is maximum”)

fnmax(11,27) # 11,27 arguments , actual value

Fruitful functions and void functions

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.

using return using print


(fruitful, more useful) (void, less useful)

def isEven(n): def isEven(n):


if (n%2 == 0): if (n%2 == 0):
return True print True
else: else:
return False print False
After all, when we test them at the Python shell prompt (like we did above), they both seem
to do exactly the same thing!
But they are NOT the same at all.
The one on the left (using return) is a fruitful function :

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

Why functions? (Advantages of function )

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.

The key aspects of the process are:

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 :

 Recursion is a way of programming or coding a problem, in which a function calls


itself one or more times in its body.
 Usually, it is returning the return value of this function call. If a function definition
fulfils the condition of recursion, we call this function a recursive function.

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

Strings and assessing string


A string is a sequence of characters. You can access the characters one at a time with the
bracket [] operator:

>>> fruit='banana'

>>> print(fruit[1])

Output
a

The expression in brackets is called an index.

To assess string we use index.

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

 A lot of computations involve processing a string one character at a time.


 Often they start at the beginning, select each character in turn, do something to it, and
continue until the end.
 This pattern of processing is called a traversal.

One way to write a traversal is with for loop .

st="hello"

i=0

for i in st:

print(i)

output:

String slices

Extracting the subset of string is called as string slice.


It can be done by using [] operator in python which is also known as slicing operator.

Syntax:
S[start:end]
This will return part of the string starting from index start to (index end -1)

>>> s = 'Monty Python'


>>> print s[0:5] #index 0 to index 4
Monty
>>> print s[6:12] #index 6 to index 11
Python
.

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:

>>> greeting = 'Tello, world!'


>>>greeting[0]=”H”

Compiler shows an error as we cannot change the created string.

In order to correct the error we have to type following


>>> new_greeting = 'H' + greeting[1:]
>>> print new_greeting
Hello, world!

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

str.find(string, beg=0, end=len(string))

string : this specifies the string to be searched


beg: this is the starting index , by default it is 0 (beginning)
end: this tis the ending index , by default it is length of the string
eg
st="hello how e"
print(st) #display sting
print(st.find('e')) #display index of e
print(st.find('e',7)) #display e after 7th index
print(st.find('e',2,4)) #find e from second index to fourth index
output
hello how e
1
10
-1 #ie not found

12
String methods :

Many built in functions are provided by Python to deal with strings


capitalize() To capitalise first letter of string
find(str,beg=0,end=len(string) Find occurrence of character in string
)
isalnum() Returns true if string has atleast 1 character and all
characters are alphanumeric and false otherwise
isalpha() Returns true if string has atleast 1 character and all
characters are alphabetic and false otherwise
isdigit() Returns true is string contains only digit else return false
islower() Returns true if string has at least 1 cased character and all
cased characters are in lowercase and false otherwise
isnumeric()
isspace() Returns true if string contains only whitespace characters
and false otherwise
isupper() Return true if string has at least one cased character and
all cased characters are in uppercase and false otherwise
len(string) Returns length of string
lower() Converts uppercase to lowercase
swapcase() Inverts case of all characters
upper() Converts to upper case

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

You might also like