1 of 189

Problem Solving and Python Programming

1

2 of 189

Strings: string slices, immutability, string functions and methods, string module

Problem Solving and Python Programming

2

3 of 189

Strings

Problem Solving and Python Programming

3

  • String is a sequence of characters.
  • String may contain alphabets, numbers and special characters.
  • Usually strings are enclosed within a single quotes and double quotes.
  • Strings is immutable in nature.
  • Example:

a="hello world"

a=‘hello world’

4 of 189

Strings Concatenation

Problem Solving and Python Programming

4

  • The + operator used for string concatenation.

Example:

a=“Hai”

b=“how are you” c=a+b

print(c)

5 of 189

Operators on String

Problem Solving and Python Programming

5

  • The Concatenate strings with the “*” operator can create multiple concatenated copies.
  • Example:

>>> print("Python"*10) PythonPythonPythonPythonPythonPython PythonPythonPythonPython

6 of 189

Operations on String

  • String Length (len( ) function)
  • String Indexing
  • String Slicing

7 of 189

String Slicing

Problem Solving and Python Programming

7

  • Slicing operation is used to return/select/slice the particular substring based on user requirements.
  • A segment of string is called slice.

8 of 189

String Slicing

Problem Solving and Python Programming

8

Python slicing can be done in two ways:

  • Using a slice() method
  • Using the array slicing  [:: ] method

9 of 189

String Slicing

Problem Solving and Python Programming

9

10 of 189

Using the slice() method�

Problem Solving and Python Programming

10

Syntax:

  • slice(stop)
  • slice(start, stop, step)

Parameters: 

start: Starting index where the slicing of object starts. 

stop: Ending index where the slicing of object stops. 

step: It is an optional argument that determines the increment between each index for slicing. 

11 of 189

# String slicing

String = 'ASTRING'

 

# Using slice constructor

s1 = slice(3)

s2 = slice(1, 5, 2)

s3 = slice(-1, -12, -2)

 

print("String slicing")

print(String[s1])

print(String[s2])

print(String[s3])

Output:

String slicing

AST

SR

GITA

12 of 189

String Slicing

Problem Solving and Python Programming

12

A start, end, and step have the same mechanism as the slice() constructor. 

  • Syntax:

string_variablename [ start:end]

13 of 189

Syntax

arr[start:stop] # items start through stop-1

arr[start:] # items start through the rest of the array

arr[:stop] # items from the beginning through stop-1

arr[:] # a copy of the whole array

arr[start:stop:step] # start through not past stop, by step

14 of 189

String Slice example

Problem Solving and Python Programming

14

s=“hello”

H

e

l

l

o

0

1

2

3

4

-5

-4

-3

-2

-1

15 of 189

Example:

String = 'GEEKSFORGEEKS’

print(String[1:5:2]) # EK

16 of 189

Strings are immutable

Problem Solving and Python Programming

16

  • Strings are immutable character sets.
  • Once a string is generated, you cannot change any character within the string.

17 of 189

Strings are immutable

  • It allows to inject items into a string

  • 3 methods are used

1) %s method

2)format( )

3)f-string method

18 of 189

String formatting using %s

Problem Solving and Python Programming

18

  • String formatting operator % is unique to strings.
  • Example:

print("My name is %s and i secured %d marks in python” % ("Arbaz",92))

  • Output:

My name is Arbaz and i secured 92 marks in python

19 of 189

print(“My name is %s and my age is %d and my percentage is %f" %("Amar",22,99.65))

Output:

My name is Amar and my age is 22 and my percentage is 99.65

20 of 189

format( ) method

The format() method formats the specified value(s) and insert them inside the string's placeholder.

Syntax:

string.format(value1, value2...)

21 of 189

txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)

txt2 = "My name is {0}, I'm {1}” .format("John",36)

txt3 = "My name is {}, I'm {}” .format("John",36)

22 of 189

myorder = "I have a {carname}, it is a {model}.”

print(myorder.format(carname = "Ford", model = Figo"))

23 of 189

f-string( ) method

  • Inserts string dynamically

  • a=“python”

print(f “I Love {a}”)

24 of 189

www.w3schools.com/python/ref_string_format.asp

25 of 189

String Comparision

Problem Solving and Python Programming

25

  • We can compare two strings using comparision operators such as ==, !=, <,<=,>, >=

  • Python compares strings based on their corresponding ASCII values.

26 of 189

Example of string comparision

Problem Solving and Python Programming

26

str1="green" str2="black"

print("Is both Equal:", str1==str2) print("Is str1> str2:", str1>str2) print("Is str1< str2:", str1<str2)

OUTPUT:

Is both Equal: False Is str1> str2: True Is str1< str2: False

27 of 189

String functions and methods

Problem Solving and Python Programming

27

len()

min()

max()

isalnum()

isalpha()

isdigit()

islower()

isuppe()

isspace()

isidentifier()

endswith()

startswith()

find()

count()

capitalize()

title()

lower()

upper()

swapcase()

replace()

center()

ljust()

rjust()

center()

isstrip()

rstrip()

strip()

28 of 189

Inbuilt String functions

Problem Solving and Python Programming

28

  • Python contains many inbuilt string functions such as:
  • They are
    • len()
    • max()
    • min()
  • len()- Find out the length of characters in string
  • min()- Smallest value in a string based on ASCII values
  • max()- Largest value in a string based on ASCII values

29 of 189

What is ASCII values

Problem Solving and Python Programming

29

30 of 189

Example for Inbuilt string functions

Problem Solving and Python Programming

30

name=input("Enter Your name:") print("Welcome",name)

print("Length of your name:",len(name)) print("Maximum value of chararacter in your name", max(name))

print("Minimum value of character in your name",min(name))

31 of 189

OUTPUT

Problem Solving and Python Programming

31

Enter Your name: PRABHAKAR Welcome PRABHAKAR

Length of your name: 9

Maximum value of chararacter in your name R Minimum value of character in your name A

32 of 189

i) Converting string functions

Problem Solving and Python Programming

32

captitalize()

Only First character capitalized

lower()

All character converted to lowercase

upper()

All character converted to uppercase

title()

First character capitalized in each word

swapcase()

Lower case letters are converted to Uppercase and Uppercase letters are converted to Lowercase

replace(old,new)

Replaces old string with new string

33 of 189

Program:

str=input("Enter any string:") print("String Capitalized:", str.capitalize()) print("String lower case:", str.lower()) print("String upper case:", str.upper()) print("String title case:", str.title()) print("String swap case:", str.swapcase())

print("String replace case:",str.replace("python","python programming"))

Problem Solving and Python Programming 18

Output:

Enter any string: Welcome to python String Capitalized: Welcome to python String lower case: welcome to python String upper case: WELCOME TO PYTHON String title case: Welcome To Python String swap case: wELCOME TO PYTHON

String replace case: Welcome to python programming

34 of 189

ii)Formatting String functions

Problem Solving and Python Programming

34

center(width)

Returns a string centered in a field of given width

ljust(width)

Returns a string left justified in a field of given width

rjust(width)

Returns a string right justified in a field of given width

format(items)

Formats a string

35 of 189

Program:

a=input("Enter any string:") print("Center alignment:", a.center(20)) print("Left alignment:", a.ljust(20)) print("Right alignment:", a.rjust(20))

Problem Solving and Python Programming

35

Output:

36 of 189

iii) Removing whitespace characters function

Problem Solving and Python Programming

36

lstrip()

Returns a string with leading whitespace characters removed

rstrip()

Returns a string with trailing whitespace characters removed

strip()

Returns a string with leading and trailing whitespace characters removed

37 of 189

Program

Problem Solving and Python Programming

37

a=input("Enter any string:") print("Left space trim:",a.lstrip()) print("Right space trim:",a.rstrip()) print("Left and right trim:",a.strip())

Output:

38 of 189

iv) Testing String/Character function

Problem Solving and Python Programming 23

isalnum()

Returns true if all characters in string are alphanumeric and there is at least one character

isalpha()

Returns true if all characters in string are alphabetic

isdigit()

Returns true if string contains only number character

islower()

Returns true if all characters in string are lowercase letters

isupper()

Returns true if all characters in string are uppercase letters

isspace()

Returns true if string contains only whitespace characters.

39 of 189

Program

Problem Solving and Python Programming

39

a=input("Enter any string:") print("Alphanumeric:",a.isalnum()) print("Alphabetic:",a.isalpha()) print("Digits:",a.isdigit()) print("Lowecase:",a.islower())

print("Upper:",a.isupper())

Output:

40 of 189

v) Searching for substring

Problem Solving and Python Programming

40

Endswith()

Returns true if the strings ends with the substring

Startswith()

Returns true if the strings starts with the substring

Find()

Returns the lowest index or -1 if substring not found

Count()

Returns the number of occurrences of substring

41 of 189

Program

Problem Solving and Python Programming

41

a=input("Enter any string:")

print("Is string ends with thon:", a.endswith("thon")) print("Is string starts with good:", a.startswith("good")) print("Find:", a.find("ython"))

print("Count:", a.count(“o"))

Output:

Enter any string : welcome to python

Is string ends with thon: True

Is string starts with good: False

Find: 12

Count: 3

42 of 189

String Methods

Problem Solving and Python Programming

42

  • In Python 1.6 and later, most string operations are made available as string methods as well.

  • Many of the functions in the string module are simply wrapper functions that call the corresponding string method.

43 of 189

Mostly used string methods are:

upper()

lower()

split()

join()

replace()

find()

count()

44 of 189

Example

text = "Monty Python Flying Circus"

# Perform various string operations directly on the string

print("Upper:", text.upper()) # Convert the string to uppercase

print("Lower:", text.lower()) # Convert the string to lowercase

print("Split:", text.split()) # Split the string into a list of words

# Join the words in the list using '+' as the separator

print("Join:", "+".join(text.split()))

# Replace occurrences of "Python" with "Java" in the string

print("Replace:", text.replace("Python", "Java"))

# Find the index of the substring "Python" in the string

print("Find:", text.find("Python"))

# Count the number of occurrences of the letter "n" in the string

print("Count:", text.count("n"))

45 of 189

Output

Problem Solving and Python Programming

45

Upper: “MONTY PYTHON FLYING CIRCUS”

Lower: “monty python flying circus”

Split: ["Monty", "Python", "Flying", "Circus"]

Join : Monty+Python+Flying+Circus Replace: Monty Java Flying Circus

Find: 7

Count: 3

46 of 189

Sample programs

1. Write a program to check given character is uppercase or lower case

2. Write a program to find a specific word in a given string and replace it with another word

3. Write a program to count the number of occurrence of specific character in a given string

4. Write a program to display the string in the following format

Hi*Everyone* I *Love*Pyton

47 of 189

48 of 189

  • List is a sequence of values called items or elements.
  • The elements can be of any data type.
  • The list is a most versatile data type available in Python which can be written as a list of comma- separated values (items) between square brackets.
  • List are mutable, meaning, their elements can be changed.

49 of 189

Method -1 without constructor

# empty list my_list = [ ]

# list of integers

my_list = [1, 2, 3]

# list with mixed datatypes my_list = [1, "Hello", 3.4]

# nested list

my_list = [“welcome", [8, 4, 6]]

Method-2 using list constructor

# empty list my_list = list()

# list of integers

my_list = list([1, 2, 3])

  • In Python programming, a list is created by placing all the items (elements) inside a square bracket [ ], separated by commas.
  • It can have any number of items and they may be of different types (integer, float, string etc.).

50 of 189

51 of 189

  • Index operator [ ] is used to access an item in a list.
  • List Index starts from 0

Example: marks=[90,80,50,70,60]

print(marks[0])

Output: 90

Nested list:

my_list = [“welcome", [8, 4, 6]]

print(marks[1][0])

Output: 8

52 of 189

  • Python allows negative indexing for its sequences.
  • The index of - 1 refers to the last item, -2 to the second last item and so on

my_list = ['p','r','o','b','e']

print(my_list[-1])

#Output: e

print(my_list[-5])

# Output: p

53 of 189

#Change Elements

>>> marks=[90,60,80]

>>> print(marks) [90, 60, 80]

>>> marks[1]=100

>>> print(marks) [90, 100, 80]

54 of 189

#Add Elements

  • add one item to a list using append() method
  • add several items using extend()
  • insert one item at a desired location by using the method insert()

>>> marks.append(50)

>>> print(marks) [90, 100, 80, 50]

>>> marks.extend([60,80,70])

>>> print(marks) [90, 100, 80, 50, 60, 80, 70]

>>> marks.insert(3,40)

>>> print(marks) [90, 100, 80, 40, 50, 60, 80, 70]

55 of 189

  • delete one or more items from a list using the keyword del.
  • It can even delete the list entirely.

>>> print(marks)

[90, 100, 80, 40, 50, 60, 80, 70]

>>> del marks[6]

>>> print(marks) [90, 100, 80, 40, 50, 60, 70]

>>> del marks

>>> print(marks)

Output: NameError: name 'marks' is not defined.

  • clear() method to empty a list.

>>> marks.clear()

>>> print(marks) # output [ ]

56 of 189

Difference b/w del and clear( )

del:

The del keyword in python deletes the objects.

clear():

clear() erases the elements in the dictionary.

57 of 189

  • remove() method to remove the given item

>>> marks=[90,60,80]

>>> marks.remove(80)

>>> print(marks) [90, 60]

>>> marks.remove(100)

Traceback (most recent call last):

File "<pyshell#1>", line 1, in <module> marks.remove(100)

ValueError: list.remove(x): x not in list

58 of 189

  • pop() method to remove an item at the given index.

>>> marks=[100,20,30]

>>> marks.pop() #30 is deleted

>>> print(marks) [100, 20]

>>> >>> marks.pop(0) #100 is deleted

>>> print(marks) [20]

59 of 189

number_list = []

n = int(input("Enter the list size "))

for i in range(0, n):

print("Enter number at index", i,)

item = int(input())

number_list.append(item)

print("User list is ", number_list)

Output:

Enter the list size 5

Enter number at index 0

55

Enter number at index 1

33

Enter number at index 2

77

Enter number at index 3

88

Enter number at index 4

1

User list is [55, 33, 77, 88, 1]

Program to receive the list elements and display

60 of 189

number_list = []

n = int(input("Enter the list size "))

for i in range(0, n):

print("Enter number at index", i, )

item = int(input())

number_list.append(item)

print("User list is ", number_list)

print("Sum = ", sum(number_list))

Output:

Enter the list size 4

Enter number at index 0

22

Enter number at index 1

11

Enter number at index 2

4

Enter number at index 3

6

User list is [22, 11, 4, 6]

Sum = 43

Program to receive the list elements and find the sum

61 of 189

  • Slicing [::] (i.e list[start:stop:step]
  • Concatenation = +
  • Repetition= *
  • Membership = in
  • Identity = is

62 of 189

63 of 189

64 of 189

65 of 189

66 of 189

67 of 189

68 of 189

69 of 189

70 of 189

71 of 189

72 of 189

73 of 189

74 of 189

75 of 189

76 of 189

77 of 189

78 of 189

79 of 189

80 of 189

81 of 189

82 of 189

Shallow copy of a list using copy() method

list=[10,20,30]

new_list=list.copy()

print(list) # [10, 20,30]

print( new_list) #[10, 20,30]

list.append(50)

print( list) #[10, 20,30, 50]

print( new_list) #[10, 20,30]

83 of 189

84 of 189

85 of 189

86 of 189

87 of 189

88 of 189

89 of 189

90 of 189

91 of 189

92 of 189

  • Tuples are very similar to lists, except that they are immutable (they cannot be changed).

  • They are created using parentheses, rather than square brackets.

93 of 189

  • We generally use tuple for heterogeneous (different) datatypes and list for homogeneous (similar) datatypes.

  • Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight performance boost.

3

94 of 189

  • A tuple is created by placing all the items (elements) inside a parentheses (), separated by comma.

  • The parentheses are optional but is a good practice to write it.

  • A tuple can have any number of items and they may be of different types (integer, float, list, string etc.).

95 of 189

96 of 189

  • Creating a tuple with one element is a bit tricky.
  • Having one element within parentheses is not enough.
  • We will need a trailing comma to indicate that it is in fact a tuple.

97 of 189

  • You can access the values in the tuple with their index, just as you did with lists
  • nested tuple are accessed using nested indexing
  • Negative indexing can be applied to tuples similar to lists.
  • We can access a range of items in a tuple by using the slicing operator
  • Trying to reassign a value in a tuple causes a TypeError.

98 of 189

99 of 189

  • Unlike lists, tuples are immutable.
  • This means that elements of a tuple cannot be changed once it has been assigned. But, if the element is itself a mutable datatype like list, its nested items can be changed. Example:

tup=(10,20,30,40)

tup[2]=50

Traceback (most recent call last):

File "<pyshell#1>", line 1, in <module>

tup[2]=50

TypeError: 'tuple' object does not support item assignment

100 of 189

  • Elements of a tuple cannot be changed once it has been assigned. But, if the element is itself a mutable datatype like list, its nested items can be changed.

101 of 189

Creating a Tuple from user Input in Python�

Examples:

my_tuple = tuple(input('Enter space-separated words: ').split())

print(my_tuple)

Output:

Enter space-separated words: 3 5 2 7 1

('3', '5', '2', '7', '1')

102 of 189

Creating a Tuple from user Input in Python�

Examples:

user_input = input('Enter space-separated integers: ')

my_tuple = tuple(int(item) for item in user_input.split())

print(my_tuple)

Output:

Enter space-separated integers: 3 4 6 7

(3, 4, 6, 7)

103 of 189

Creating a Tuple from user Input in Python�

user_input = input('Enter space-separated integers: ')

my_tuple = tuple(int(item) for item in user_input.split())

print(my_tuple)

c=my_tuple[0]+my_tuple[1]

print(“Result=“,c)

Output:

Enter space-separated integers: 3 4 6 7

(3, 4, 6, 7)

Result=7

104 of 189

Similar to List,

  • We can use + operator to combine two tuples. This is also called concatenation.
  • We can also repeat the elements in a tuple for a given number of times using the * operator.
  • Both + and * operations result into a new tuple.

105 of 189

  • We cannot change the elements in a tuple. That also means we cannot delete or remove items from a tuple.
  • But deleting a tuple entirely is possible using the keyword del.

106 of 189

  • Methods that add items or remove items are not available with tuple. Only the following two methods are available.

Method

Description

Return the number of items that is equal to x

Return index of first item that is equal to x

107 of 189

  • We can test if an item exists in a tuple or not, using the keyword in.

108 of 189

  • Using a for loop we can iterate though each item in a tuple.

109 of 189

Function

Description

Return True if all elements of the tuple are true (or if the tuple is empty).

Return True if any element of the tuple is true. If the tuple is empty, return False.

Return an enumerate object. It contains the index and value of all the items of

tuple as pairs.

Return the length (the number of items) in the tuple.

Return the largest item in the tuple.

Return the smallest item in the tuple

Take elements in the tuple and return a new sorted list (does not sort the tuple itself).

Retrun the sum of all elements in the tuple.

Convert an iterable (list, string, set, dictionary) to a tuple.

110 of 189

Try all the built-in functions with example.

111 of 189

Example

Converting list to tuple and tuple to list

tup=(10,20,30)

print(list(tup)) # [10, 20, 30]

print(tuple(tup)) #(10, 20, 30)

112 of 189

  1. Write a program to find maximum and minimum in a given tuple
  2. Write a program to find sum of values in a given tuple using function
  3. Write a program to sort the tuple using sort() and sorted() methods

113 of 189

user_input = input('Enter space-separated integers: ')

my_tuple = tuple(int(item) for item in user_input.split())

print(my_tuple)

print(max(my_tuple))

print(min(my_tuple))

114 of 189

def summation(test_tup):

    # Initializing count

    count = 0

    for i in test_tup:

        count += i

    return count

# Initializing test_tup

test_tup = (5, 20, 3, 7, 6, 8)

print(summation(test_tup))

115 of 189

tuple_ = (52243167)  

sorted_ = tuple(sorted(tuple_))  

print('Sorted Tuple :', sorted_)  

print(type(sorted_)) 

OR

tuple_ = ('Itika''Arshia''Peter''Parker')  

list(tuple_).sort()   

print(tuple_)  

print(type(tuple_)) 

116 of 189

117 of 189

  • Sets are used to store multiple items in a single variable.

  • Set is one of 4 built-in data types in Python used to store collections of data

  • A set is a collection which is unorderedunchangeable*, and unindexed.

  • Set items are unchangeable, but you can remove items and add new items.

118 of 189

  • A set is created by placing all the elements inside curly braces { }, separated by comma or by using the built-in function set().

  • The elements can be of different types (integer, float, tuple, string etc.).

  • But a set cannot have a mutable element, like list, set or dictionary, as its element.

119 of 189

120 of 189

  • Set items are unordered, unchangeable, and do not allow duplicate values.
  • Example:

set={1,1,2,2,3}

print(set)

Output:

{1, 2, 3}

121 of 189

The values True and 1 are considered the same value in sets, and are treated as duplicates:

Example:

set={"apple""banana""cherry"True12}��print(set)

Output:

{True, 2, 'banana', 'cherry', 'apple'}

122 of 189

A set can contain elements of different type

A set cannot contain lists.

123 of 189

  • Since sets are unordered, indexing have no meaning.

  • We cannot access or change an element of set using indexing or slicing.

  • We can add single element using the add() method and multiple elements using the update() method.

  • The update() method can take tuples, lists, strings or other sets as its argument.

124 of 189

125 of 189

  • A particular item can be removed from set using methods, discard() and remove().

  • using discard() if the item does not exist in the set, it remains unchanged.

  • But remove() will raise an error in such condition.

126 of 189

127 of 189

128 of 189

  • We can test if an item exists in a set or not, using the in operator.

129 of 189

  • To determine how many items a set has, use the len() function.

  • Example:

thisset = {"apple", "banana", "cherry"}

print(len(thisset))

Get the Length of a Set using len()

130 of 189

  • Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric difference.
  • We can do this with operators or methods.

Method

Operator

union

|

intersection

&

difference

-

symmetric_difference

^

131 of 189

132 of 189

133 of 189

134 of 189

Create 3 lists namely TCS, Infosys, Wipro with some set of students in each list. Convert the lists to set. Now print the students placed in any of these companies with count.

135 of 189

136 of 189

137 of 189

  • A dictionary is a kind of data structure that stores items in key-value pairs.
  • A key is a unique identifier for an item, and a value is the data associated with that key.

  • A dictionary has a key: value pair.

  • Dictionaries are optimized to retrieve values when the key is known.

138 of 189

  • Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
  • Each element in a dictionary is represented by a key:value pair.
  • While values can be of any data type and can repeat, keys must be of immutable type and must be unique.

3

139 of 189

3

140 of 189

  • While indexing is used with other container types to access values, dictionary uses keys.
  • Key can be used either inside square brackets or with the get() method.

  • The difference while using get() is that it returns None instead of KeyError, if the key is not found.

141 of 189

3

142 of 189

  • Dictionary are mutable. We can add new items or change the value of existing items using assignment operator.

  • If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.

143 of 189

144 of 189

  • We can remove a particular item in a dictionary by using the method pop(). This method removes as item with the provided key and returns the value.

  • All the items can be removed at once using the clear() method.

  • We can also use the del keyword to remove individual items or the entire dictionary itself.

145 of 189

146 of 189

147 of 189

  • The method, popitem() can be used to remove and return an arbitrary item (key, value) form the dictionary.
  • Raises KeyError if the dictionary is empty.

148 of 189

  • To remove a entry from dictionary, we can use del method.
  • Remove norway
  • del (countryCapitals[‘norway’])

149 of 189

150 of 189

  • # Definition of country and capital
  • countries=['france', 'germany', 'norway', 'india']
  • capitals = ['paris', 'berlin', 'oslo','delhi']
  • I would like to print the capital of germany.

# Get index of 'germany': ind_ger

# Use ind_ger to print out capital of Germany

151 of 189

152 of 189

153 of 189

  • We can test if a key is in a dictionary or not using the keyword in. Notice that membership test is for keys only, not for values.

154 of 189

  • Using a for loop we can iterate through each key in a dictionary.

Output:

Maths

Science

Social

Output:

maths : 45

science : 23

social : 55

155 of 189

156 of 189

Method

Description

Remove all items form the dictionary.

Return a shallow copy of the dictionary.

Return a new dictionary with keys from seq and value equal to v(defaults to None).

Return the value of key. If key doesnot exit, return d (defaults to None).

Return a new view of the dictionary's items (key, value).

Return a new view of the dictionary's keys.

Remove the item with key and return its value or d if key is not found. If d is not provided and key is not found, raises KeyError.

Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty.

If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None).

Update the dictionary with the key/value pairs from other, overwriting existing keys.

Return a new view of the dictionary's values

157 of 189

Function

Description

Return the length (the number of items) in the dictionary.

Return a new sorted list of keys in the dictionary.

158 of 189

  • If you know how to access a dictionary, you can also assign a new value to it. To add a new key-value pair to countryCapitals, you can use something like this:

countryCapitals[‘india’] = ‘delhi’

159 of 189

  • Create a dictionary for a country with their capital. Write a code to search for a country , if present display the capital else a message saying not present

160 of 189

161 of 189

  • Dictionaries can contain key:value pairs where the values are again dictionaries.

162 of 189

Files

163 of 189

    • File is a named location on disk to store related information.
    • Data for python program can come from difference sources such as keyboard, text file, web server, database.
    • Files are one such sources which can be given as input to the python program. Hence handling files in right manner is very important.

164 of 189

    • Primarily there are two types of files
      • Text files : A text file can be thought of as a sequence of lines without any images, tables etc. These files can be create by using some text editors.

 

      • Binary files : These files are capable of storing text, image, video, audio, database files, etc which contains the data in the form of bits.

 

165 of 189

    • To perform read or write operation on a file, first file must be opened.
    • A file can be opened using a built-in function open( ).
    • Syntax:

fhand= open(“filename”, “mode”)

    • fhand -> It is a reference to a file object, which acts as a handler for all further operations on files.

Opening files

166 of 189

OR

fhand = open('c:/users/roopa/desktop/sample.txt')

fhand = open(‘sample.txt’)

Print(fhand)

167 of 189

Mode

Meaning

 

r

Opens a file for reading purpose. If the specified file does not exist in the

specified path, or if you don‟t have permission, error message will be displayed. This is the default mode of open() function in Python.

 

w

Opens a file for writing purpose. If the file does not exist, then a new file with the given name will be created and opened for writing. If the file

already exists, then its content will be over-written.

 

A

Opens a file for appending the data. If the file exists, the new content will

be appended at the end of existing content. If no such file exists, it will be created and new content will be written into it.

r+

Opens a file for reading and writing.

 

w+

Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and

writing.

 

a+

Opens a file for both appending and reading. The file pointer is at the end

of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading

Rb

Opens a file for reading only in binary format

Wb

Opens a file for writing only in binary format

Ab

Opens a file for appending only in binary format

168 of 189

Reading files

  • There are several ways to read the contents of the file

  1. using the file handle as the sequence in for loop.

 

sample.txt

Python is a high level programming language it is introduced by Guido van rossam.

Python is easy to learn and simple to code an application

169 of 189

Print_count.py

fhand = open('sample.txt’)

count = 0

for line in fhand:

count = count + 1

print('Line :', count, line) print('LineCount:', count)

fhand.close()

Output:

 

Line : 1 Python is a high level programming language

Line : 2 it is introduced by Guido van rossam.

Line : 3 Python is easy to learn and simple to code an application

 

Line Count: 3

170 of 189

2. The second way of reading a text file loads the entire file into a string :�

You can read the whole file into one string using the read method on the file handle.

171 of 189

Letting the user choose the file name�

fname =input('Enter the file name: ‘)

fhand = open(fname)

172 of 189

Writing files

write a file, you have to open it with mode “w” as a second parameter:

fout = open('output.txt', 'w’)

print(fout)

<_io.TextIOWrapper name='output.txt’

mode='w' encoding='cp1252’>

  • If the file already exists, opening it in write mode clears

out the old data and starts fresh, If the file doesn’t exist, a

new one is created.

173 of 189

line1 = “Hello,How are you\n"

fout.write(line1)

Closing a file:

fout.close( )

174 of 189

Append mode

When the file is opened in append mode, the handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data. 

# Append-adds at last

file1 = open("myfile.txt", "a") # append mode

file1.write("Today \n")

file1.close()

175 of 189

PYTHON-INHERITANCE

176 of 189

What is Inheritance

Inheritance is the ability to ‘inherit’ features or attributes from already

attributes are defined data structures and the functions we

written classes into newer classes we make. These features and

can

perform with them, a.k.a. Methods. It promotes code reusability, which is considered one of the best industrial coding practices as it makes the codebase modular.

In python inheritance, new class/es inherits from older class/es. The new class/es copies all the older class's functions and attributes without rewriting the syntax in the new class/es. These new classes are called derived classes, and old ones are called base classes.

177 of 189

Types of Inheritance in Python

  1. Single Inheritance
  2. Multiple Inheritance
  3. Multi Level Inheritance
  4. Hierarchical Inheritance in Python
  5. Hybrid Inheritance in Python

Parent1 -> Child1 : Single Inheritance

Parent1 -> Child1 -> Child2 : Multi – Level Inheritance Parent1 -> Child2 <- Parent2 : Multiple Inheritance

178 of 189

Single Inheritance in python

Single Inheritance is the simplest form of inheritance where a single child class is derived from a single parent class. Due to its candid nature, it is also known as Simple Inheritance.

179 of 189

Single Inheritance Example

180 of 189

Multiple Inheritance in Python

In multiple inheritance, a single child class is inherited from two or more parent classes. It means the child class has access to all the parent classes' methods and attributes.

181 of 189

Multiple Inheritance Example

182 of 189

Multilevel Inheritance in Python

In multilevel inheritance, we go beyond just a parent-child relation. We introduce grandchildren, great-grandchildren, grandparents, etc. We have seen only two levels of inheritance with a superior parent class/es and a derived class/es, but here we can have multiple levels where the parent class/es itself is derived from another class/es.

183 of 189

Example for MultiLevel Inheritance

184 of 189

Hierarchical Inheritance

Hierarchical Inheritance is the right opposite of multiple inheritance. It means that, there are multiple derived child classes from a single parent class.

185 of 189

Example for Hierarchical Inheritance

186 of 189

Hybrid Inheritance in Python

Hybrid Inheritance is the mixture of two or more different types of inheritance. Here we can have many relationships between parent and child classes with multiple levels.

187 of 189

Example for Hybrid Inheritance

188 of 189

Advantage of Inheritance in Python

Increases modularity, i.e., breaking down codebase into modules, making it easier to understand. Here, each class we define becomes a separate module that can be inherited separately by one or many classes.

Code Reusability: the child class copies all the attributes and methods of the parent class into its class and use. It saves time and coding effort by not rewriting them, thus following modularity paradigms.

Modular Codebase:

Less Development and Maintenance Costs:

changes need to be made in the base class; all

derived classes will automatically follow.

189 of 189

Disadvantage of Inheritance in Python

Decreases the Execution Speed: loading multiple classes because they are interdependent

Tightly Coupled Classes: this means that even though parent classes can be executed independently, child classes cannot be executed without defining their parent classes.