0% found this document useful (0 votes)
18 views23 pages

PPS Unit 3 Notes

Unit III covers the concepts of functions and strings in Python, emphasizing the importance of functions for code reusability and modularity. It explains the definition, scope, and usage of functions, including lambda functions, and details string operations, immutability, and formatting. Additionally, it lists built-in string methods and their functionalities.

Uploaded by

itsmedon09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views23 pages

PPS Unit 3 Notes

Unit III covers the concepts of functions and strings in Python, emphasizing the importance of functions for code reusability and modularity. It explains the definition, scope, and usage of functions, including lambda functions, and details string operations, immutability, and formatting. Additionally, it lists built-in string methods and their functionalities.

Uploaded by

itsmedon09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Department of First Year Engineering

Programming and Problem Solving


Unit- 3 Notes

Unit III: Functions and Strings


Need for functions, Function: definition, call, variable scope and lifetime, the return statement.
Defining functions, Lambda or anonymous function, documentation string, good programming
practices.
Introduction to modules, Introduction to packages in Python, Introduction to standard library modules.
Strings and Operations- concatenation, appending, multiplication and slicing. Strings are immutable,
strings formatting operator, built in string methods and functions. Slice operation, ord() and chr()
functions, in and not in operators, comparing strings, Iterating strings, the string module.

3.1 Functions

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 enclosed by {}. 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.

3.1.1 Need of Functions


• By using functions, we can avoid rewriting same logic/code again and again in a program.
• We can call python functions any number of times in a program and from any place in a program.
• We can track a large python program easily when it is divided into multiple functions.

1 Unit III: Functions and Strings FE PPS 2024


• Reusability is the main achievement of python functions.
• However, Function calling is always overhead in a python program.

3.1.2 Functions definition

You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
• Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these parentheses. You can also define
parameters inside these parentheses.
• The first statement of a function can be an optional statement - the documentation string of the
function or doc string.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression to the caller.
A return statement with no arguments is the same as return None.

Syntax:-
def function-name(parameter):
Instruction to be processed.
Return statement

2 Unit III: Functions and Strings FE PPS 2024


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

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

Example 1
def print_message():
message = "hello !! I am going to print a message." # the variable message is local to the function
itself
print(message) print_message()
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/[Link]", line 5, in print(message)
NameError: name 'message' is not defined

Example 2
def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)
sum=0
3 Unit III: Functions and Strings FE PPS 2024
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum) # 0 will be printed
Output:
The sum is 60
Value of sum outside the function: 0
3.1.3 Lambda or anonymous function

• The anonymous function contains a small piece of code


• These functions are called anonymous because they are not declared in the standard manner by using
the def keyword. You can use the lambda keyword to create small anonymous functions.
• Lambda forms can take any number of arguments.
• Return just one value in the form of an expression.
• They cannot contain commands or multiple expressions.
• An anonymous function cannot be a direct call to print because lambda requires an expression
• Lambda functions have their own local namespace and cannot access variables other than those in
their parameter list and those in the global namespace.
• Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline
statements in C or C++, whose purpose is by passing function stack allocation during invocation for
performance reasons.

Syntax:-

E.g. lambda arguments : expression


x = lambda a:a+10
print("sum = ",x(20))

E.g.
x = lambda a,b:a+b
print("sum = ",x(20,10))

4 Unit III: Functions and Strings FE PPS 2024


Why to use lambda
When we want to execute some task with in function with some input which will be processing
parameter passed to function.

E.g.

def myfunc(n):
return lambda a : a * n

x = myfunc(2) // will execute first fun with parameter 2 then it passed on to


lambda with x i.e. 11
print(x(11))

5 Unit III: Functions and Strings FE PPS 2024


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

o Example:
string = 'Welcome'
print(string[0])#Accessing string with index print(string[1])
print(string[2])
print(srting[0:2]) #Accessing string with range slice method
6 Unit III: Functions and Strings FE PPS 2024
Output:
w
e
l
wel

c. Deleting/Updating from a String:


o In Python, updating or deletion of characters from a String is not allowed as Strings are immutable.
o Although deletion of entire String is possible with the use of a built-in del keyword.
o Example:
string='welcome'
del string

Q 2. Explain Operations on string.:


Operation Description Example Output
Concatenation(+) -It joins two strings and x="Good" Good Morning
returns new list. y="Morning"
z=x+y
print(z)

Append (+=) -Append x="Good" Good Morning


operation adds y="Morning"
one string at the x+=y
end of another print(x)
string
Repetition(*) -It repeats elements x="Hello" HelloHello
from the strings n y=x*2
number of times print(y)

7 Unit III: Functions and Strings FE PPS 2024


Slice [] - It will give you x="Hello" e
character from a print(x[1])
specified index.

Range slice[:] -It will give you x="Hello" He


characters from print(x[0:2])
specified range slice.

3.2 Strings are immutable

Q 3. Python strings are immutable. Comment on this. Ans:


• Python Strings are immutable, which means that once it is created it cannot be changed.
• Whenever you try to change/modify an existing string, a new string is created.
• As every object (variable) is stored at some address in computer memory.
• The id() function is available in python which returns the address of object(variable) in memory. With
the help of memory locations/address we can see that for every modification, string get new address
in memory.
• Here is the example to demonstration the address change of string after modification.
# prints string1 and its address
string1="Good"
print("String1 value is: ",string1)
print("Address of string1 is: ",id(string1)

# prints string2 and its address


string2="Morning"
print("String2 value is: ",string2)
print("Address of string2 is: ",id(string2)

8 Unit III: Functions and Strings FE PPS 2024


#appending string1 to string2
string1+= string2
print("String1 value is: ",string1)
print("Address of string1 is: ",id(string1)

Output:
String1 value is: Good
Address of String1 is: 1000

String2 value is: Morning


Address of String1 is: 2000

String1 value is: GoodMorning


Address of String1 is: 3000

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

3.3 Strings formatting operator


Q 4. Explain various ways of string formatting with example.:
• In python, % sign is a string formatting operator.
• 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.

9 Unit III: Functions and Strings FE PPS 2024


• 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

%u Unsigned decimal integer

%o Octal integer

%x or %X Hexadecimal integer

%e or %E Exponential notation

%f Floating point number

%g or %G Short numbers in floating point or exponential notation

Example: Program to use format sequences while printing a string.


name="Amar"
age=8
print("Name = %s and Age = %d" %(name,age))
print("Name = %s and Age = %d" %("Ajit",6))

10 Unit III: Functions and Strings FE PPS 2024


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.

3.2 Built-in String methods and functions

Q 5. List and explain any 5 string methods. Or


Q. Explain the use of ( ) with the help of an example. Ans.

Sr. Function Usage Example

No.
1 capitalize() This function is used to capitalize first letter of str="hello" print([Link]())
string. output:
Hello

2 isalnum() Returns true if string has at least 1 character and message="JamesBond007"


every character is either a number or an alphabet print([Link]()) output:
and True
False otherwise.
3 isalpha() Returns true if string has at least 1 character and message="JamesBond007"
every character is an alphabet and False print([Link]()) output:
otherwise. False

11 Unit III: Functions and Strings FE PPS 2024


4 isdigit() Returns true if string has at least 1 character and message="007"
every character is a digit and False otherwise. print([Link]()) output:
True

5 islower() Returns true if string has at least 1 message="Hello"


character and every character is a print([Link]()) output:
lowercase alphabet and False otherwise. False
6 isspace() Returns true if string contains only white space message=" "
character and False otherwise. print([Link]()) output:
True
7 isupper() Returns true if string has at least 1 character and message="HELLO"
every character is an uppercase alphabet and print([Link]()) output:
False True
otherwise.
8 len(string) Returns length of the string. str="Hello" print(len(str)) output:
5
9 zfill(width) Returns string left padded with zeros to a total str="1234" print([Link](10)) output:
of width characters. It is used with numbers and 0000001234
also
retains its sign (+ or -).
10 lower() Converts all characters in the string into str="Hello" print([Link]()) output:
lowercase. hello
11 upper() Converts all characters in the string into str="Hello" print([Link]()) output:
uppercase. HELLO
12 lstrip() Removes all leading white space in string. str=" Hello" print([Link]()) output:
Hello
13 rstrip() Removes all trailing white space in string. str=" Hello " print([Link]())
output:
Hello

12 Unit III: Functions and Strings FE PPS 2024


14 strip() Removes all leading white space and trailing str=" Hello " print([Link]()) output:
white space in string. Hello
15 max(str) Returns the highest alphabetical character str="hello friendz" print(max(str))
(having highest ASCII value) from the string str. output:
z
16 min(str) Returns the lowest alphabetical character str="hellofriendz" print(min(str))
(having lowest ASCII value) from the string str. output:
d
17 replace(old,ne Replaces all or max (if given) occurrences of str="hello hello hello"
w[, max]) old in string with new. print([Link]("he","Fo")) output:
Follo Follo Follo
18 title() Returns string in title case. str="The world is beautiful"
print([Link]())
output:
The World Is Beautiful
19 swapcase() Toggles the case of every character (uppercase str="The World Is Beautiful"
character becomes lowercase and vice versa). print([Link]()) output:
tHE wORLD iS
bEAUTIFUL
20 split(delim) Returns a list of substrings str="abc,def, ghi,jkl"
separated by the specified delimiter. If no print([Link](',')) output:
delimiter is 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 function joins print('-'.join(['abc', 'def', ' ghi',
a list of strings using delimiter with which the 'jkl']))
function output:
is invoked. abc-def- ghi-jkl
22 isidentifier() Returns true if the string is a valid identifier. str="Hello" print([Link]())

13 Unit III: Functions and Strings FE PPS 2024


output:
True
23 enumerate(str) Returns an enumerate object that lists the index str="Hello World"
and value of all the characters in the string as print(list(enumerate(str))) output:
pairs. [(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.

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

Program to demonstrate slice operation on string objects

14 Unit III: Functions and Strings FE PPS 2024


str=”PYTHON”
print(“str[1:5]= “, str[1:5]) #characters start at index 1 and extending upto index 4
# but not including index 5
print(“str[ :6]= “, str[ :6]) # By defaults indices start at index 0
print(“str[1: ]= “, str[1: ]) # By defaults indices ends upto last index
print(“str[ : ]= “, str[ : ]) # By defaults indices start at index 0 and end upto last
#character in the string
#negative index
print(“str[-1]= “, str[ -1]) # -1 indicates last character
print(“str[ :-2 ]= “, str[ : -2]) #all characters upto -3
print(“str[ -2: ]= “, str[ -2: ]) #characters from index -2
print(“str[-5 :-2 ]= “, str[ -5: -2]) # characters from index -5 upto character index -3

OUTPUT str[1:5]= YTHO


str[ :6]= PYTHON
str[1: ]= YTHON
str[ : ]= PYTHON
str[-1]= N
str[ :-2 ]= PYTH
str[ -2: ]= ON
str[-5 :-2 ]= YTH

Specifying Stride while Slicing Strings


• In the slice operation, you can specify a third argument as the stride, which refers to the number of
characters to move forward after the first character is retrieved from the string.
• The default value of stride is 1, i.e. where value of stride is not specified, its default value of 1 is
used which means that every character between two index number is retrieved.

15 Unit III: Functions and Strings FE PPS 2024


Program to use slice operation with stride
str=” Welcome to the world of Python“
print(“str[ 2: 10]= “, str[2:10]) #default stride is 1
print(“str[ [Link] ]= “, str[Link]) #same as stride=1
print(“str[ [Link] ]= “, str[Link]) #skips every alternate character
print(“str[ [Link] ]= “, str[Link]) #skips every fourth character

OUTPUT
str[ 2: 10]=lcome to str[ 2: 10]= lcome to
str[ [Link] ]=loet
str[ [Link] ]=l
• Whitespace characters are skipped as they are also part of the string.

4.6ord() and chr() functions


Q [Link] a short note on ord() and chr() functions Ans.
• The ord() function return the ASCII code of the character
• The chr() function returns character represented by a ASCII number.

ch=’R’ print(chr(82)) print(chr(112)) print(ord(‘p’))

print(ord(ch))

OUTPUT OUTPUT OUTPUT OUTPUT

82 R p 112

16 Unit III: Functions and Strings FE PPS 2024


4.7 in and not in operators

Q [Link] a short note on in and not in operators OR


[Link] the help of example, explain significance of membership operators. Ans.
• in and not in operators can be used with strings to determine whether a string is present in another
string. Therefore the in and not in operator is known as membership operators.

• For example:

str1=” Welcome to the world of Python!!!“ str1=” This is very good book“ str2=”best”
str2=”the” 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”

OUTPUT OUTPUT
False True

17 Unit III: Functions and Strings FE PPS 2024


4.8 Comparing strings
Q 9. Explain string comparison operator with example? Ans.
➢ Python allows us to combine strings using relational (or comparison) operators such as >, <, <=,>=,
etc.
➢ Some of these operators along with their description and usage are given as follows:
Operator Description Example
== If two strings are equal, it returns True. >>>”AbC”==”AbC”
True
!= or <> If two strings are not equal, it returns True. >>>”AbC”!=”Abc”
True
> If the first string is greater than the second, it >>>”abc”>”Abc”
returns True. True
< If the second string is greater than the first, it >>>”abC”<”abc”
returns True. True
>= If the first string is greater than or equal to >>>”aBC”>=””ABC”
the second, it returns True. True
<= If the second string is greater than or equal to >>>”ABc”<=”ABc”
the first, it returns True. 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.

String Comparison Programming Examples: (Any one)


➢ There are different ways of comparing two strings in Python programs:

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

18 Unit III: Functions and Strings FE PPS 2024


• 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

• Example2(Checking Case Sensitivity):


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

19 Unit III: Functions and Strings FE PPS 2024


Output:
First String: Kunal works at PHOENIX
Second String: Kunal works at Phoenix
LBoth 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

➢ Using the is operator for comparing two strings:


• The is operator compares two variables based on the object id and returns True if the two variables
refer to the same object.
• Example:
name1=”Kunal”
name2=”Shreya”
print(“name1:”,name1)

20 Unit III: Functions and Strings FE PPS 2024


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:


i) for loop with example
ii) while loop with example
➢ String is a sequence type (sequence of characters).
➢ We can iterate through the string using:

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-

21 Unit III: Functions and Strings FE PPS 2024


str=”Welcome to python”
for i in str:
print(i,end=’ ’)

Output-
Welcome to Python

ii) while loop:


• We can also iterate through the string using while loop by writing the following code.
• Example-
message=” Welcome to python”
index=0
while index < len(message):
letter=message[index]
print(letter,end=’ ‘)
index=index+1

Output-
Welcome to Python

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

4.10 The string module


Q. No. 11 Write a note on string module?
➢ The string module consists of a number of useful constants, classes and functions.
➢ These functions are used to manipulate strings.

22 Unit III: Functions and Strings FE PPS 2024


➢ 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.
• [Link]: A string that has all the characters that are considered lowercase letters.
• [Link]: A string that has all the characters that are considered uppercase letters.
• [Link]:Refers to digits from 0-9.
• [Link]: Refers to hexadecimal digits,0-9,a-f, and A-F.
• [Link]: Refers to octal digits from 0-7.
• [Link]: String of ASCII characters that are considered to be punctuation characters.
• [Link]: String of printable characters which includes digits, letters, punctuation, and
whitespaces.
• [Link]: 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-“, [Link]())
print(“Lowercase-“, [Link]())
print(“Split-“, [Link]())
print(“Join-“, ‘-‘.join([Link]()))
print(“Replace-“,[Link](“Python”,”Java”))
print(“Count of o-“, [Link](‘o’))
print(“Find of-“,[Link](“of”))

23 Unit III: Functions and Strings FE PPS 2024

You might also like