unit-3 python
unit-3 python
3.1 String
We can create a string by enclosing the characters in single-quotes or double- quotes. Python also
provides triple-quotes to represent the string, but it is generally used for multiline string or
docstrings.
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
41
String with the use of Single Quotes:
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
Creating a multiline String:
Geeks
For
Life
3.1.4.String Slicing
● In Python, the String Slicing method is used to access a range of characters in the String. Slicing
in a String is done by using a Slicing operator, i.e., a colon (:).
● One thing to keep in mind while using this method is that the string returned after slicing
includes the character at the start index but not the character at the last index.
42
Figure 3.2 String Slicing
Example 1
Output:
A character of a string can be updated in Python by first converting the string into a Python List and then
updating the element in the list. As lists are mutable in nature, we can update the character and then convert
the list back into the String.
43
# Updating a character of the String
## As python strings are immutable, they don't support item updation directly
### there are following two ways
#way1
list1 = list(String1)
list1[2] = 'p'
String2 = ''.join(list1)
print("\nUpdating character at 2nd Index: ")
print(String2)
#way 2
String3 = String1[0:2] + 'p' + String1[3:]
print(String3)
Output:
Initial String:
Hello, I'm a Geek
Updating character at 2nd Index:
Heplo, I'm a Geek
Heplo, I'm a Geek
As we know that strings are immutable. We cannot delete or remove the characters from
the string. But we can delete the entire string using the del keyword.
Output:
Output:
44
3.1.7 Escape Sequencing in Python
● While printing Strings with single and double quotes in it causes SyntaxError
because String already contains Single and Double Quotes and hence cannot be printed
with the use of either of these.
● Escape sequences start with a backslash and can be interpreted differently. If single
quotes are used to represent a string, then all the single quotes present in the string
must be escaped and the same is done for Double Quotes.
Example
String1= "C:\\Python\\Geeks\\"
print(String1)
print(String1)
Output
45
Letcure 13. Python List & List Slicing
3.2 List-
● The list is a sequence data type which is used to store the collection of data.
● In lists the comma (,)and the square brackets [enclose the List's items] serve as separators.
● Lists need not be homogeneous always which makes it the most powerful tool in Python.
● A single list may contain DataTypes like Integers, Strings, as well as Objects.
● Lists are mutable, and hence, they can be altered even after their creation.
A list may contain duplicate values with their distinct positions and hence, multiple distinct or
duplicate values can be passed as a sequence at the time of list creation.
Example-
List1=[“physics”, “Maths”,34,15.5]
List2=[2,3,5,10]
The indexing procedure is carried out similarly to string processing. The slice operator [] can be
used to get to the List's components.
46
We can get the sub-list of the list using the following syntax.
o Within a start, the step is used to skip the nth element: stop.
Example-
List1=[0,1,2,3,4]
List1[1:3:1]= [1,2]
List = []
print("Initial blank List: ")
print(List)
List.append(1)
List.append(2)
print("List after Addition of Three elements: ")
print(List)
List.insert(2, 12)
List.extend([8, 'Geeks'])
print("List after performing Extend Operation: ")
print(List)
Elements can be removed from the List by using the built-in remove() function but an
Error arises if the element doesn’t exist in the list.
List = [1, 2, 3, 4, 5]
List.pop()
print("List after popping an element: ")
print(List)
List.pop(2)
print("\nList after popping a specific element: ")
print(List)
48
3.3 List Operations-
49
3.5 List Built In Methods-
50
51
Lecture 14. How to Use of Tuple data type
3.6 Tuple
Note: Creation of Python tuple without the use of parentheses is known as TuplePacking.
52
Note: We can change any python collection like (list, tuple, set) and string into other data
type like tuple, list and string. But cannot change into and float to any python collection. For
example: int cannot change into list or vice-versa.
Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. The entire tuple
gets deleted by the use of del() method.
53
3.6.1 Tuple Operations
54
3.7 The zip() Function
The zip() is an inbuilt function in python. It takes items in sequence from a number of
collections to make a list of tuples, where each tuple contains one item from each collection.
The function is often used to group items from a list which has the same index.
Example:
A=[1,2, 3]
B=’XYZ’
Res=list(zip(A,B)) # list of tuples
print(Res)
Output:
[(1, 'X'), (2, 'Y'), (3, 'Z')]
55
Python program to find the maximum and minimum K elements in a tuple
Output
56
Lecture 15. String and string manipulation methods.
3.8 string manipulation methods-
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where
it was found
index() Searches the string for a specified value and returns the position of where
it was found
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
islower() Returns True if all characters in the string are lower case
57
isupper() Returns True if all characters in the string are upper case
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
2. WAP to accept a string & replace all spaces by # without using string method.
58
Lecture 16 Python Set and list manipulating methods
3.9 Set- set is an unordered collection of data items which does not contain duplicate values.
Every set element is unique and must be immutable (cannot be changed). However, a set
itself is mutable. Elements of set are enclosed inside a pair of curly brackets {}.
We can add and remove items from the set. But cannot replace item as it does not support
indexing of data items.
Empty set is created by:
A=set()
print(A)
Outpu t:
Set()
Output:
apple
banan a
cherry
59
NOTE: Lists cannot be added to a set as elements because Lists are not hashable whereas
Tuples can be added because tuples are immutable and hence Hashable.
● Elements can be removed from the Set by using the built-in remove() function but
a KeyError arises if the element doesn’t exist in the set.
● To remove elements from a set without KeyError, use discard(), if the element
doesn’t exist in the set, it remains unchanged.
60
Note: If the set is unordered then there’s no such way to determine which
element is popped by using the pop() function.
61
Examples:
S1={1,2,3,4,5}
S1.remove(2)
print(S1)
Output:
{1,3,4,5}
S1={1,2,3,4}
S2={1,2,3,4,5}
print(S1.issubset(S2))
Output:
True
print(S2.issuperset(S1))
Output:
True
>>>
S1={1,2,3,4,5}
S2={5,6,7}
print(S1.union(S2)) #
print(S1|S2)
Output:
{1,2,3,4,5,6,7}
>>>
print(S1.intersection(S2)) #
print(S2&S2)
Output:
{5}
>>>
print(S1.difference(S2))
print(S1-S2)
Output:
{1,2,3,4}
62
>>>
print(S1.symmetric_difference(S2))
print(S1^S2)
Output:
{1,2,3,4,6,7}
63
Lecture 17. Python Dictionary and its manipulation method
In order to access the items of a dictionary refer to its key name. Key can be used inside
square brackets. . Following is a simple example −
There is also a method called get() that will also help in accessing the element from a
dictionary.This method accepts key as argument and returns the value.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "White"})
Keyword
The items of the dictionary can be deleted by using the del keyword
Output
65
cmp(dict1, dict2)
1
Compares elements of both dict.
len(dict)
2 Gives the total length of the dictionary. This would be equal to the number
of items in the dictionary.
str(dict)
3
Produces a printable string representation of a dictionary
type(variable)
4
Returns the type of the passed variable. If passed variable is dictionary,
then it would return a dictionary type.
Method Description
67
Lecture 18. Function
3.15 Function.
Master code
def sum(x,y):
s=0
for i in range(x,y+1):
s-s+i
Output:
sum of integers from x to y : 1625
Function calling is called driver code and function definition with block of statements is called master
code
68
3.16 Differentiate between argument and parameter.
• Formal parameter
• Actual Parameter
Formal parameters are those written in function definition and actual
parameters are those written in function calling.
Formal parameters are called argument.
Arguments are the values that are passed to function definition.
Example:
Def fun(n1):
Print(n1)
a=10
fun(a)
here n1 is argument and a is parameter.
Ans:
69
70
def display(a='hello',b='world'): # you can have only default arguments
print(a,b)
display()
Output:
hello world
71
def display(a,c=10,b): # default argument will always come as last argument
d=a+b+c
print(d)
def display(a,b,c=10):
d=a+b+c
print(d)
display(2, 3)
Output:
15
72
variable length argument Example:
def display(*arg):
for i in arg:
print(i)
display(‘hello’,’world’)
Output:
hello
world
73
The Return Statement:The return statement is used to return a value from the function to a
calling function. It is also used to return from a function i.e. break out of the function.
Example:
square,cube=compute(2)
74
Lecture 19. Anonymous function
3.19 Anonymous Function
75
Program to find cube of a number using lambda function
cube=lambda x:
x*x*x
print(cube(2))
Output:
8
Note:
● The statement cube=lambda x: x*x*x creates a lambda function called cube, which
takes a single argument and returns the cube of a number.
Q6. Define scope of a variable. Also differentiate local and global variable.
Ans:
76
1. Program to access a local variable outside a functions
def demo():
q=10
print("the value of local variable is",q)
demo()
77
demo()
Output:
I love python
s=’I love
python print(s)
Output:
I love python
I love programming
Example:
a=20
def display():
global a
a=30
print(‘value of a is’,a)
display()
Output:
value of a is 30
Note:
Since the value of the global variable is changed within the function, the value
of ‘a’ outside the function will be the most recent value of ‘a’
78
Lecture 20. Recursion Function
3.20 Recursion-
def factorial(n):
return 1
return n * factorial(n-1)
print(factorial(5))
Output:
120
Note: Recursion ends when the number n reduces to 1. This is called base condition. Every
recursive function must have a base condition that stops the recursion or else the function
calls itself infinitely.
Ans:
def fibonacci(n):
if(n <= 1):
79
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
print("Fibonacci sequence:")
for i in range(n):
print(fiboncci(i)
,
Ans:
def gcd(a,b):
if(b==0):
returna
else:
return gcd(b,a%b)
a=int(input("Enter first number:"))
GCD=gcd(a,b)
print("GCD is: )
print(GCD)
Ans:
def sum_arr(arr,size):
if (size == 0):
return 0
else:
80
for i in range(0,n):
element=int(input("Enter element:"))
a.append(element)
print("The list is:")
print(a)
print("Sum of items in list:")
b=sum_arr(a,n)
print(b)
Q11. Program to check whether a string is a palindrome or not using recursion. Ans:
def is_palindrome(s):
if len(s) < 1:
return True
else:
if s[0] == s[-1]:
return is_palindrome(s[1:-1])
else:
return False
a=str(input("Enter string:"))
if(is_palindrome(a)==True):
print("String is a palindrome!")
else:
81