Python_Module2_Notes
Python_Module2_Notes
MODULE II
FUNCTIONS
Creation of functions
Passing parameters and return values
STRINGS
String Manipulation
String methods
FUNCTIONS
len(): This function takes a single argument and finds its length. The argument can be a string, list,
tuple etc.
len(“hello how are you?”)
18
There are many other built-in functions available in Python. They are discussed in further Modules,
wherever they are relevant.
Type Conversion Functions
As we have seen earlier (while discussing input() function), the type of the variable/value can be
converted using functions int(), float(), str().
Python provides built-in functions that convert values from one type to another
Consider following few examples –
By default, this function generates a random number between 0.0 and 1.0 (excluding 1.0).
For example –
import random #module random is imported
print(random.random()) #random() function is invoked
0.7430852580883088 #a random number generated
print(random.random())
0.5287778188896328 #one more random number
Importing a module creates an object.
Using this object, one can access various functions and/or variables defined in that module.
Functions are invoked using a dot operator.
There are several other functions in the module random apart from the function random(). (Do not
get confused with module name and function name. Observe the parentheses while referring a
function name).
Few are discussed hereunder:
randint(): It takes two arguments low and high and returns a random integer between these two
arguments (both low and high are inclusive). For example,
>>>random.randint(2,20)
14 #integer between 2 and 20 generated
>>> random.randint(2,20)
10
Various other functions available in random module can be used to generate random numbers following
several probability distributions like Gaussian, Triangular, Uniform, Exponential, Weibull, Normal etc
Math Functions
Python provides a rich set of mathematical functions through the module math.
To use these functions, the math module has to be imported in the code.
Some of the important functions available in math are given hereunder
sqrt(): This function takes one numeric argument and finds the square root of that argument.
>>> math.sqrt(34) #integer argument
5.830951894845301
>>> math.sqrt(21.5) #floating point argument
4.636809247747852
log10(): This function is used to find logarithm of the given argument, to the base 10.
>>> math.log10(2)
0.3010299956639812
log(): This is used to compute natural logarithm (base e) of a given number.
>>> math.log(2)
0.6931471805599453
sin(): As the name suggests, it is used to find sine value of a given argument. Note that, the argument
must be in radians (not degrees). One can convert the number of degrees into radians by multiplying
pi/180 as shown below –
>>>math.sin(90*math.pi/180) #sin(90) is 1
1.0
pow(): This function takes two arguments x and y, then finds x to the power of y.
>>> math.pow(3,4)
81.0
User-defined Functions
Python facilitates programmer to define his/her own functions.
The function written once can be used wherever and whenever required.
The syntax of user-defined function would be –
def fname(arg_list):
statement_1
statement_2
……………
Statement_n
return value
return is a keyword used to return the output value. This statement is optional
The first line in the function def fname(arg_list)is known as function header/definition. The
remaining lines constitute function body.
The function header is terminated by a colon and the function body must be indented.
To come out of the function, indentation must be terminated.
Unlike few other programming languages like C, C++ etc, there is no main()
function or specific location where a user-defined function has to be called.
The programmer has to invoke (call) the function wherever required.
Consider a simple example of user-defined function –
def myfun():
Observe indentation
print("Hello") print("Inside
- Statements outside the function without
the function")
indentation.
print("Example of function")
myfun() myfun()is called here.
print("Example over")
Here, the first output indicates that myfun is an object which is being stored at the memory address
0x0219BFA8 (0x indicates octal number).
The second output clearly shows myfun is of type function.
(NOTE: In fact, in Python every type is in the form of class. Hence, when we apply type on any
variable/object, it displays respective class name. The detailed study of classes will be done in Module
4.)
The flow of execution of every program is sequential from top to bottom, a function can be invoked
only after defining it.
Dept of ECE, BNMIT Page 6
Python Programming on Raspberry PI -22ECE136 Module II
Usage of function name before its definition will generate error. Observe the following code:
print("Example of function")
myfun() #function call before definition
print("Example over")
The output is –
Example of function Inside
myfun() Inside repeat()
Inside myfun() Example
over
Observe the output of the program to understand the flow of execution of the program.
Initially, we have two function definitions myfun()and repeat()one after the other. But, functions are
not executed unless they are called (or invoked). Hence, the first line to execute in the above program
is –
print("Example of function")
Then, there is a function call repeat(). So, the program control jumps to this function. Inside
repeat(), there is a call for myfun().
Now, program control jumps to myfun()and executes the statements inside and returns back to
def test(var):
print("Inside test()")
print("Argument is ",var)
def test(var):
print("Inside test()")
print("Argument is ",var)
One can observe that, when the argument is of type string, then multiplication indicates that string is
repeated 3 times.
Whereas, when the argument is of numeric type (here, integer), then the value of that argument is
literally multiplied by 3.
A function that performs some task, but do not return any value to the calling function is known as
void function. The examples of user-defined functions considered till now are void functions.
The function which returns some result to the calling function after performing a task is known as
fruitful function.
One can write a user-defined function so as to return a value to the calling function as shown in
the following example –
def sum(a,b):
return a+b
x=int(input("Enter a number:"))
y=int(input("Enter another number:"))
s=sum(x,y)
print("Sum of two numbers:",s)
The sample output would be –
Enter a number:3
STRINGS
A string is a sequence of characters, enclosed either within a pair of single quotes or double
quotes.
Each character of a string corresponds to an index number, starting with zero as shown below:
S= “Hello World”
character H e l l o w o r l d
index 0 1 2 3 4 5 6 7 8 9 10
The characters of a string can be accessed using index enclosed within square brackets.
So, H is the 0th letter, e is the 1th letter and l is the 2th letter of “Hello world”
For example,
>>> word1="Hello"
>>> word2='hi'
>>> x=word1[1] #2nd character of word1 is extracted
>>> print(x)
e
>>> y=word2[0] #1st character of word1 is extracted
>>> print(y)
h
Python supports negative indexing of string starting from the end of the string as shown below:
S= “Hello World”
character H e l l o w o r l d
Negative index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
The characters can be extracted using negative index also, which count backward from the end of
the string.
For example:
>>> var=“Hello”
>>> print(var[-1])
o
>>> print(var[-4])
e
Whenever the string is too big to remember last positive index, one can use negative index to
extract characters at the end of string.
Output:
H e l l o
In the above example, the for loop is iterated from first to last character of the string st. That is, in
every iteration, the counter variable i takes the values as H, e, l, l and o. The loop terminates when
no character is left in st.
Using while loop:
st="Hello"
i=0
while i<len(st):
print(st[i], end=’\t’)
i+=1
Output:
H e l l o
In this example, the variable i is initialized to 0 and it is iterated till the length of the string. In every
iteration, the value of i is incremented by 1 and the character in a string is extracted using i as index.
Example: Write a while loop that starts at the last character in the string and traverses backwards to
the first character in the string, printing each letter on separate line
str="Hello"
i=-1
while i>=-len(str):
print(str[i])
i-=1
Output:
o
l
l
e
H
String Slices
A segment or a portion of a string is called as slice.
Only a required number of characters can be extracted from a string using colon (:) symbol.
The basic syntax for slicing a string would be – st[i:j:k]
This will extract character from ith character of st till (j-1)th character in steps of k.
If first index is not present, it means that slice should start from the beginning of the string. I
f the second index j is not mentioned, it indicates the slice should be till the end of the string.
The third parameter k, also known as stride, is used to indicate number of steps to be incremented
after extracting first character. The default value of stride is 1.
Consider following examples along with their outputs to understand string slicing.
st="Hello World" #refer this string for all examples
8. print(st[3:8:2]) #output is l o
Starting from 3rd character, till 7th character, every alternative index is considered.
of negative indexing) till 10th character (which is also the last character in positive indexing) in
incremental order of 1. Hence, we will get only last character as output.
By the above set of examples, one can understand the power of string slicing and of Python script. The
slicing is a powerful tool of Python which makes many task simple pertaining to data types like strings,
Lists, Tuple, Dictionary etc. (Other types will be discussed in later Modules)
def count(st,ch):
cnt=0
for i in st:
if i==ch:
cnt+=1
return cnt
st=input("Enter a string:")
ch=input("Enter a character to be counted:")
c=count(st,ch)
print("%s appeared %d times in %s"%(ch,c,st))
Output:
Enter a string: hello how are you?
Enter a character to be counted: h
h appeared 2 times in hello how are you?
The in Operator
The in operator of Python is a Boolean operator which takes two string operands.
It returns True, if the first operand appears as a substring in second operand, otherwise returns
False.
For example,
String Comparison
Basic comparison operators like < (less than), > (greater than), == (equals) etc. can be applied on
string objects.
Such comparison results in a Boolean value True or False.
Internally, such comparison happens using ASCII codes of respective characters.
Consider following examples –
Output is same. As the value contained in st and hello both are same, the equality results in True.
Output is greater. The ASCII value of h is greater than ASCII value of H. Hence, hello
is greater than Hello.
NOTE: A programmer must know ASCII values of some of the basic characters. Here are few –
A–Z : 65 – 90
a–z : 97 – 122
0–9 : 48 – 57
Space 32
Enter Key 13
String Methods
String is basically a class in Python.
When we create a string in program, an object of that class will be created.
A class is a collection of member variables and member methods (or functions).
When we create an object of a particular class, the object can use all the members (both variables
and methods) of that class.
Python provides a rich set of built-in classes for various purposes. Each class is enriched with a
useful set of utility functions and variables that can be used by a Programmer.
A programmer can create a class based on his/her requirement, which are known as user-defined
classes.
The built-in set of members of any class can be accessed using the dot operator as shown–
objName.memberMethod(arguments)
The dot operator always binds the member name with the respective object name. This is very
essential because, there is a chance that more than one class has members with same name. To
avoid that conflict, almost all Object oriented languages have been designed with this common
syntax of using dot operator.
Python provides a function (or method) dir to list all the variables and methods of a particular class
object. Observe the following statements –
[' add ', ' class ', ' contains ', ' delattr ', ' dir ', ' doc ', ' eq ', ' format ', ' ge ', ' getattribute ',
' getitem ', ' getnewargs ', ' gt ', ' hash ', ' init ', ' init_subclass ', ' iter ', ' le ', ' len ', ' lt ',
' mod ', ' mul ', ' ne ', ' new ', ' reduce ', ' reduce_ex ', ' repr ', ' rmod ', ' rmul ', ' setattr
', ' sizeof ', ' str ', ' subclasshook ', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
Note that, the above set of variables and methods are common for any object of string class that
we create.
Each built-in method has a predefined set of arguments and return type.
To know the usage, working and behavior of any built-in method, one can use the command help.
For example, if we would like to know what is the purpose of islower() function (refer above list
to check its existence!!), how it behaves etc, we can use the statement –
>>> help(str.islower)
Help on method_descriptor:
islower(...)
S.islower() -> bool
Return True if all cased characters in S are lowercase and if there is at least one upper
cased character in S, returns False otherwise.
Observe in Ex2 that the first character is converted to uppercase, and an in-between uppercase
letter W of the original string is converted to lowercase.
s.upper(): This function returns a copy of a string s to uppercase. As strings are immutable, the
original string s will remain same.
>>> st='HELLO'
>>> st1=st.lower()
>>> print(st1) hello
>>> print(st) #no change in original string
HELLO
s.find(s1) : The find() function is used to search for a substring s1 in the string s. If found, the
index position of first occurrence of s1 in s, is returned. If s1 is not found in s, then -1 is returned.
>>> st='hello'
>>> i=st.find('l')
>>> print(i) #output is 2
>>> i=st.find('lo')
>>> print(i) #output is 3
>>> print(st.find(‘x’)) #output is -1
The find() function can take one more form with two additional arguments viz. start and end positions
for search.
>>> st="calender of Feb. cal of march"
>>> i= st.find(‘cal’)
>>> print(i) #output is 0
Here, the substring „cal‟is found in the very first position of st, hence the result is 0.
>>> i=st.find('cal',10,20)
>>> print(i) #output is 17
Here, the substring cal is searched in the string st between 10th and 20th position and hence the result
is 17.
>>> i=st.find('cal',10,15)
>>> print(i) #output is -1
In this example, the substring 'cal' has not appeared between 10th and 15th character of st. Hence,
the result is -1.
s.strip(): Returns a copy of string s by removing leading and trailing white spaces.
The startswith() function requires case of the alphabet to match. So, when we are not sure about the
case of the argument, we can convert it to either upper case or lowercase and then use
startswith()function as below –
>>> st="Hello"
>>> st.startswith("he") #returns False
>>> st.lower().startswith("he") #returns True
S.count(s1, start, end): The count() function takes three arguments – string, starting position and
ending position. This function returns the number of non-overlapping occurrences of substring s1 in
string S in the range of start and end.
>>> st="hello how are you? how about you?"
>>> st.count('h') #output is 3
>>> st.count(‘how’) #output is 2
>>> st.count(‘how’,3,10) #output is 1 because of range given
Example:
st=input("Enter a string:")
ch=input("Enter a character to be counted:")
c=st.count(ch)
print("%s appeared %d times in %s"%(ch,c,st))
Parsing Strings
Sometimes, we may want to search for a substring matching certain criteria.
For example, finding domain names from email-Ids in the list of messages is a useful task in some projects.
Consider a string below and we are interested in extracting only the domain name.
print(host)
Output:
Position of @ is 10
Position of space after @ is 22
bnmit.ac.in
Format Operator
The format operator, % allows us to construct strings, replacing parts of the strings with the data stored in
variables.
The first operand is the format string, which contains one or more format sequences that specify how the
second operand is formatted.
Syntax: “<format>” % (<values>)
The result is a string.
>>> sum=20
**** ****