Unit 3 Notes - Functions and Strings
Unit 3 Notes - Functions and Strings
Advantages
• Reducing duplication of code
• Decomposing complex problems into simpler pieces
• Improving clarity of the code
• Reuse of code
• Information hiding
1
• Understanding, coding and testing multiple separate functions are far easier than
doing the same for one huge function.
• If big program has to be developed without the use of any function, then there
will be large number of lines in the code and maintaining that program will be a
big mess.
• All the libraries in Python contains pre-defined and pre-tested functions which the
programmers are free to use directly in their programs without worrying about
their code in detail.
• When a big program is broken into comparatively smaller functions, then
different programmers working on that project can divide the workload by writing
different functions.
• Like Python libraries, programmers can also make their own functions and use
them from different points in the main program or any other program that needs
its functionalities.
• Code Reuse: Code reuse is one of the prominent reason to use functions. Large
programs follow DRY principle i.e. Don’t Repeat Yourself principle. Once a
function is written, it can be called multiple times within the same or by different
program wherever its functionality is needed. Correspondingly, a bad repetitive
code abides by WET principle i.e. Write Everything Twice or We Enjoy Typing.
If a set of instructions have to be executed abruptly from anywhere within the
program code, then instead of writing these instructions everywhere they are
required, a better way is to place these instructions in a function and call that
function wherever required.
3.2Function Definition
Q. What is user defined function? With the help of example illustrate how you can
have such functions in your program.
OR
Q. Explain with example how to define and call a function?
Ans:
2
To define user defined function following points must be considered:
• Function blocks start with the keyword def
• The keyword is followed by the function name and parenthesis ( ) . The function
name is uniquely identifying the function.
• After the parenthesis a colon (:) is placed
• Parameters or arguments that function accepts are placed within parenthesis.
They are optional.
• The first statement of a function can be n optional statement-the documentation
string of the function or docstring describe what the function does.
• The code block within the function is properly indented to form the block code.
• A function may have a return[expression] statement. It is optional.
Syntax:
def function_name(variable1, variable2,..): Function Header
Documentation string
Statement block
return [expression] Function Boy
• Function call statement has the following syntax when it accepts parameters
function_name(variable1, variable2,..)
3
OUTPUT
10
4
• In this example, we can observe that the value of x is 10 initially.
• Then the var_scope() function is called, it has the value of x as 5, but it is only inside
the function.
• It did not affect the value outside the function.
• This happens since the variable x inside the function var_scope() is considered as
different (local to the function) from the one outside.
• Although they have same names, they are two different variables with different
scope.
5
• For ex.
x=”Good”
def show()
global y
y = “Morning”
print(“In function x is – “, x)
show()
print(“Outside function y is – “, y) # accessible as it is global variable
print(“ x is – “, x)
Output:
In function x is- Good
Outside function y is – Morning
x is - Good
Ans:
• If we have variable with same name as Global and Local variable. Then local
variable is accessible within the function/block in which it is defined.
• Global variable is defined outside of any function and accessible throughout the
program.
• In the code given below, str is a global string because it has been defined before
calling the function.
• Program that demonstrates using a variable defined in global namespace.
6
def fun():
print(str)
str = “Hello World!!!”
fun()
Output:
Hello World
• You cannot define a local variable with the same name as that of global variable. If
you want to do that you just use the global statement.
• Program describes using a local variable with same name as that of global
def f():
global str
print(str)
str= “hello world”
print(str)
7
• In the example below we can see there is no return statement used.
• So here default return none is used as last statement, and program will execute
successfully.
def func1():
x=5
print(“Value of x: ”,x)
func1()
print(“Hello World!)
Output:
Value of x: 5
Hello World
• So from this we can say that return statement is optional in function definition.
Q. Write a note on return statement with suitable example.
Ans:
• In python, every function is expected to have return statement.
• When we do not specify return statement at the end of our function, Implicit return
statement is used as last statement for such function.
• This implicit return statement returns nothing to its caller, so it is said to return none.
• But you can change this default behavior by explicitly using the return statement to
return some value to the caller.
Output:
Cube of 10 = 100
Note: return statement cannot be used outside the function.
9
Ans: There are four types of function arguments available in Python as follow:
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1. Required Arguments:
• In the required arguments, the arguments are passed to the function in correct
positional order.
• The number of arguments in the function call should exactly match with the
number of arguments specified in the function definition
• For ex.
def person(name, age):
print(name)
print( age)
person(“Amar”, 20)
Output:
Amar
20
2. Keyword Arguments:
• In keyword arguments the order(or position) of the arguments can be changed.
• The values are assigned to the arguments by using their names
• The python interpreter uses keywords provided in the function call to match the
values with parameters.
• Program to demonstrate keyword arguments
def person(name, age, salary):
print(“Name: ”, name)
print(“Age: ”, age)
print(“Salary: ”, salary)
10
Output:
Name: Ajay
Age: 30
Salary: 50000
• Note:
o All the keyword arguments passed should match one of the arguments
accepted by the function
o The order of keyword argument is not important
o In no case argument should receive a value more than once
3. Default Arguments:
• Python allows user to specify function arguments that can have default
values
• Function call can have less number of arguments than provided in its
definition.
• User can specify default value for one or more arguments which is used if no
value provided in call for that argument.
def display(name, age=18):
print(“Name: ”+ name)
print(“Age: ”, age)
display(age=25, name=”Ajay”)
display(”Amar”)
Output:
Name: Ajay
Course: 25
Name: Amar
Course: 18
• In the above example, default value is not specified for name, so it is mandatory.
11
• But age has provided default value, so if value not provided in calling for age, it will
take 18.
Note: Non default arguments should be provided before default arguments.
• In the above program, in the function definition we have two parameters- one is a
and other is variable length parameter tup.
• The first value is assigned to a and other values are assigned to parameter tup.
• In tup parameter, 0 to n values are acceptable.
• The variable length argument if present in the function definition should be the last
in the list of formal parameters.
• To see or use all the values in the variable length parameter, we have to use for loop
as given in above example.
12
3.6 Lambda or Anonymous functions
Q. What is lambda or anonymous functions in python? Explain with example.
Ans.
• Lambda or anonymous function have no name.
• They are created using lambda keyword instead of def.
• Lambda function contains only single line.
• Lambda function can take any number of arguments.
• It can returns only one value in the form of an expression.
• Lambda function does not have explicit return statement.
• Lambda function cannot contain multiline expressions.
• It cannot access variable other than those in their parameter list
• We can pass Lambda function as arguments in other functions.
• Syntax:
Lambda arguments: expression
Output:
Sum=8
13
3.7 Documentation String
Q. What are docstring?
Ans:
• Docstrings (documentation string) serves the same purpose as that of comments.
• Docstrings are designed to explain code.
• Docstrings are created by putting multiline string to explain the code.
• Docstrings are important as they help tools to automatically generate printed
documentation
• Docstrings are very helpful to readers and users of the code to interactively browse
the code.
• Docstrings specified in function can be accessed through the doc attributes of
the functions.
• Unlike comments, Docstrings are retained throughout the runtime of the program.
(Docstrings ignored by the compilers)
• Syntax:
def function_name(parameters):
""" Function written for factorial,
Calculates factorial of number """
Function statements
return [expression]
• Example:
def func():
""" function just prints message.
It will display Hello World !! """
print(“Hello World!!”)
func( )
print(func. doc )
Output:
Hello World!!
function just prints message.
It will display Hello World !!
14
3.8 Good Programming Practices
Q. Write a note on good programming practices in python.
Ans:
To develop readable, effective and efficient code programmer has to take care of following
practices:
• Instead of tabs, use 4 spaces for indentations.
• Wherever required use comments to explain code.
• Use space around operators and after commas.
• Name of the function should be in lower case with underscore to separate words
Eg. get_data()
• Use document string that explains purpose of the functions
• Name of the class should be written as first letter capital in each word
Eg. ClassName()
• Do not use non ASCII character in function names or any other identifier.
• Inserts blank lines to separate functions, Classes, and statement blocks inside
functions
15
o To use a module in any program, add import module_name as the first line in your
program.
Syntax:
import module_name
o Then module_name.var is written to access functions and values with the name var
in the module.
16
o A compiled version of module with file extension .pyc is generated.
o Next time when the module is imported, this .pyc file is loaded instead of .py
file.
o A new compiled version of a module is again produced whenever the
compiled module is out of date.
o Even the programmer can force the python shell to reload and recompile
the .py file to generate a new .pyc file by using reload( ) function.
• To import more than one item from a module, use comma separated list. For
example, to import value of pi and sqrt( ) from math module write:
Example:
from math import pi, sqrt
print("PI= ", pi)
print("Square root of 4=", sqrt(4))
Output:
PI= 3.141592653589793
Square root of 4= 2.0
17
• To import all identifiers defined in a module, except those beginning with
underscore ( _ ), use import * statement.
• Example:
from math import *
print("PI= ", pi)
print("Square root of 4=", sqrt(4))
Output:
PI= 3.141592653589793
Square root of 4= 2.0
• Then open another file (main.py) and write code given below.
File Name: main.py
import Mymodule
print("Mymodule string=", Mymodule.str)
Mymodule.display()
• Modules should be placed in the same directory as that of the program in which it is
imported.
• It can also be stored in one of the directories listed in sys.path.
• The dot operator is used to access members (variables or functions) of module.
3.10 Packages
Q. What are packages in python?
Ans:
• A package is a hierarchical file directory structure.
• A package has modules and other packages within it.
• Every package in python is a directory which must have a special file called
init .py. This may not even have a single line of code.
• It is simply added to indicate that this is not an ordinary directory and contains a
Python package.
• A package can be accessed in other python program using import statement.
• For example, to create a package MyPackage, create directory called MyPackage
having module MyModule and init .py file.
File Name: Mymodule.py
def display():
19
print("Hello")
str = "Welcome to World of Python"
• Now, to use MyModule in a program, import it in any one of the two ways:
import MyPackage.MyModule
or
from MyPackage import MyModule
20
Strings
4.1 Strings and Operations
Q 1. What is String? With the help of example explain how we can create string
variable in python.
Ans:
• Strings data type is sequence of characters, where characters could be letter, digit,
whitespace or any other symbol.
a. Creation of Strings:
o Strings in Python can be created using single quotes or double quotes or even
triple quotes.
o Example:
string1 = 'Welcome' # Creating a String with single Quotes
string2 = "Welcome" # Creating a String with double Quotes
string3 = '''Welcome''' # Creating a String with Triple Quotes
b. Accessing strings:
o In Python, individual characters of a String can be accessed by using the method
of Indexing or range slice method [:].
o Indexing allows negative address references to access characters from the back
of the String, e.g. -1 refers to the last character, -2 refers to the second last
character and so on.
String W E L C O M E
Indexing 0 1 2 3 4 5 6
Negative Index -7 -6 -5 -4 -3 -2 -1
1
PPS Unit-VI RMD Warje
o Example:
string = 'Welcome'
print(string[0]) #Accessing string with index
print(string[1])
print(string[2])
print(string[0:2]) #Accessing string with range slice method
Output:
w
e
l
we
2
Append (+=) -Append operation x="Good" Good Morning
adds one string at y="Morning"
the end of another x+=y
string print(x)
Repetition(*) -It repeats elements x="Hello" HelloHello
from the strings n y=x*2
number of times print(y)
Slice [] - It will give you x="Hello" e
character from a print(x[1])
specified index.
3
# prints string2 and its address
string2="Morning"
print("String2 value is: ",string2)
print("Address of string2 is: ",id(string2))
Output:
String1 value is: Good
Address of String1 is: 1000
• From the above output you can see string1 has address 1000 before modification. In
later output you can see that string1 has new address 3000 after modification.
• It is very clear that, after some operations on a string new string get created and it has
new memory location. This is because strings are unchangeable/ immutable in nature.
Modifications are not allowed on string but new string can be created at new address
by adding/appending new string.
4
• The % operator takes a format string on the left and the corresponding values in a
tuple on the right.
• The format operator, % allows users to replace parts of string with the data stored in
variables.
• The syntax for string formatting operation is:
"<format>" % (<values>)
• The statement begins with a format string consisting of a sequence of characters and
conversion specification.
• Following the format string is a % sign and then a set of values, one per conversion
specification, separated by commas and enclosed in parenthesis.
• If there is single value then parenthesis is optional.
• Following is the list of format characters used for printing different types of data:
Format Purpose
Symbol
%c Character
%d or %i Signed decimal integer
%s String
%o Octal integer
%x or %X Hexadecimal integer
%e or %E Exponential notation
5
Output:
Name = Amar and Age = 8
Name = Ajit and Age = 6
In the output, we can see that %s has been replaced by a string and %d has been replaced by
an integer value.
6
character and every character is a print(message.islower())
lowercase alphabet and False output:
otherwise. False
6 isspace() Returns true if string contains only message=" "
white space character and False print(message.isspace())
otherwise. output:
True
7 isupper() Returns true if string has at least 1 message="HELLO"
character and every character is an print(message.isupper())
uppercase alphabet and False output:
otherwise. True
8 len(string) Returns length of the string. str="Hello"
print(len(str))
output:
5
9 zfill(width) Returns string left padded with str="1234"
zeros to a total of width characters. print(str.zfill(10))
It is used with numbers and also output:
retains its sign (+ or -). 0000001234
10 lower() Converts all characters in the string str="Hello"
into lowercase. print(str.lower())
output:
hello
11 upper() Converts all characters in the string str="Hello"
into uppercase. print(str.upper())
output:
HELLO
12 lstrip() Removes all leading white space in str=" Hello"
string. print(str.lstrip())
output:
Hello
7
13 rstrip() Removes all trailing white space in str=" Hello "
string. print(str.rstrip())
output:
Hello
14 strip() Removes all leading white space str=" Hello "
and trailing white space in string. print(str.strip())
output:
Hello
15 max(str) Returns the highest alphabetical str="hello friendz"
character (having highest ASCII print(max(str))
value) from the string str. output:
z
16 min(str) Returns the lowest alphabetical str="hellofriendz"
character (having lowest ASCII print(min(str))
value) from the string str. output:
d
17 replace(old,new[, max]) Replaces all or max (if given) str="hello hello hello"
occurrences of old in string with print(str.replace("he","Fo"))
new. output:
Follo Follo Follo
18 title() Returns string in title case. str="The world is beautiful"
print(str.title())
output:
The World Is Beautiful
19 swapcase() Toggles the case of every character str="The World Is
(uppercase character becomes Beautiful"
lowercase and vice versa). print(str.swapcase())
output:
tHE wORLD iS
bEAUTIFUL
20 split(delim) Returns a list of substrings str="abc,def, ghi,jkl"
8
separated by the specified print(str.split(','))
delimiter. If no delimiter is output:
specified then by default it splits ['abc', 'def', ' ghi', 'jkl']
strings on all whitespace
characters.
21 join(list It is just the opposite of split. The print('-'.join(['abc', 'def', '
function joins a list of strings using ghi', 'jkl']))
delimiter with which the function output:
is invoked. abc-def- ghi-jkl
22 isidentifier() Returns true if the string is a valid str="Hello"
identifier. print(str.isidentifier())
output:
True
23 enumerate(str) Returns an enumerate object that str="Hello World"
lists the index and value of all the print(list(enumerate(str)))
characters in the string as pairs. output:
[(0, 'H'), (1, 'e'), (2, 'l'), (3,
'l'), (4, 'o'), (5, ' '), (6, 'W'),
(7, 'o'), (8, 'r'), (9, 'l'), (10,
'd')]
4.5Slice operation
Q 6. What is slice operation? Explain with example.
Ans.
Slice: A substring of a string is called a slice.
A slice operation is used to refer to sub-parts of sequences and strings.
Slicing Operator: A subset of a string from the original string by using [] operator
known as Slicing Operator.
9
Indices in a String
Index from
P Y T H O N
the start
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
Index from
Syntax:
the end
string_name[start:end]
where start- beginning index of substring
end -1 is the index of last character
OUTPUT
str[1:5]= YTHO
str[ :6]= PYTHON
str[1: ]= YTHON
str[ : ]= PYTHON
10
str[-1]= N
str[ :-2 ]= PYTH
str[ -2: ]= ON
str[-5 :-2 ]= YTH
OUTPUT
str[ 2: 10]=lcome to
str[ 2: 10]= lcome to
str[ 2:10:2 ]=loet
str[ 2:10:4 ]=l
• Whitespace characters are skipped as they are also part of the string.
•
4.6ord() and chr() functions
Q 7.Write a short note on ord() and chr() functions
Ans.
• The ord() function return the ASCII code of the character
11
• The chr() function returns character represented by a ASCII number.
• For example:
str1=” Welcome to the world of Python!!!“ str1=” This is very good book“
str2=”the” str2=”best”
if str2 in str1: if str2 in str1:
print(“found”) print(“found”)
else: else:
print(“Not found”) print(“Not found”)
OUTPUT OUTPUT
Found Not found
• You can also use in and not in operators to check whether a character is present in a
word.
• For example:
‘u‘ in “starts” ‘v‘ not in “success”
12
OUTPUT OUTPUT
False True
➢ These operators compare the strings by using ASCII value of the characters.
➢ The ASCII values of A-Z are 65-90 and ASCII code for a-z is 97-122.
➢ For example, book is greater than Book because the ASCII value of ‘b’ is 98 and ‘B’
is 66.
13
➢ Using the ==(equal to) operator for comparing two strings:
• If we simply require comparing the values of two variables then you may use
the ‘==’ operator.
• If strings are same, it evaluates to True, otherwise False.
• Example1:
first_str='Kunal works at Phoenix'
second_str='Kunal works at Phoenix'
print("First String:", first_str)
print("Second String:", second_str)
#comparing by ==
if first_str==second_str:
print("Both Strings are Same")
else:
print("Both Strings are Different")
Output:
First String: Kunal works at Phoenix
Second String: Kunal works at Phoenix
Both Strings are Same
14
Output:
First String: Kunal works at PHOENIX
Second String: Kunal works at Phoenix
Both Strings are Different
➢ Using the !=(not equal to) operator for comparing two strings:
• The != operator works exactly opposite to ==, that is it returns true is both
the strings are not equal.
• Example:
first_str='Kunal works at Phoenix'
second_str='Kunal works at Phoenix'
print("First String:", first_str)
print("Second String:", second_str)
#comparing by !=
if first_str!=second_str:
print("Both Strings are Different")
else:
print("Both Strings are Same")
output:
First String: Kunal works at Phoenix
Second String: Kunal works at Phoenix
Both Strings are Same
15
print(“name2:”,name2)
print(“Both are same”,name1 is name2)
name2=”Kunal”
print(“name1:”,name1)
print(“name2:”,name2)
print(“Both are same”,name1 is name2)
• Output:
name1=Kunal
name2=Shreya
Both are same False
name1=Kunal
name2=Kunal
Both are same True
• In the above example, name2 gets the value of Kunal and subsequently
name1 and name2 refer to the same object.
•
4.9 Iterating strings
Q. No.10 How to iterate a string using:
Ans.
i) for loop with example
ii) while loop with example
Ans.
i) for loop:
• for loop executes for every character in str.
• The loop starts with the first character and automatically ends when
the last character is accessed.
• Example-
16
str=”Welcome to python”
for i in str:
print(i,end=’ ’)
Output-
We lco me to Pyt hon
• In the above program the loop traverses the string and displays each
letter.
• The loop condition is index < len(message), so the moment index
becomes equal to the length of the string, the condition evaluates to
False, and the body of the loop is not executed.
• Index of the last character is len(message)-1.
17
➢ String Constants: Some constants defined in the string module are:
• string.ascii_letters: Combination of ascii_lowecase and ascii_uppercase
constants.
• string.ascii_lowercase: Refers to all lowercase letters from a-z.
• string.ascii_uppercase: Refers to all uppercase letters from A-Z.
• string.lowercase: A string that has all the characters that are considered
lowercase letters.
• string.uppercase: A string that has all the characters that are considered
uppercase letters.
• string.digits:Refers to digits from 0-9.
• string.hexdigits: Refers to hexadecimal digits,0-9,a-f, and A-F.
• string.octdigits: Refers to octal digits from 0-7.
• string.punctuation: String of ASCII characters that are considered to be
punctuation characters.
• string.printable: String of printable characters which includes digits, letters,
punctuation, and whitespaces.
• string.whitespace: A string that has all characters that are considered
whitespaces like space, tab, return, and vertical tab.
➢ Example: (Program that uses different methods such as upper, lower, split, join,
count, replace, and find on string object)
str=”Welcome to the world of Python”
print(“Uppercase-“, str.upper())
print(“Lowercase-“, str.lower())
print(“Split-“, str.split())
print(“Join-“, ‘-‘.join(str.split()))
print(“Replace-“,str.replace(“Python”,”Java”))
print(“Count of o-“, str.count(‘o’))
print(“Find of-“,str.find(“of”))
18