Module 2
Module 2
Module 2
Data Structures: Lists: The List Data Type, Working with Lists Strings: Manipulating Strings,
Working with Strings, Useful String Methods Tuples and Dictionaries, basics Using Data
Structures to Model Real-World Things, Manipulating Strings.
>>> print(list3)
[100, 23.5, 'Hello']
#list4 is the list of lists called nested list
>>> list4 =[['Physics',101],['Chemistry',202], ['Maths',303]]
>>> print(list4)
[['Physics', 101], ['Chemistry', 202], ['Maths', 303]]
Say you have the list ['cat', 'bat', 'rat', 'elephant'] stored in a variable
named spam.
The Python code spam[0] would evaluate to 'cat', and spam[1] would
evaluate to 'bat', and so on.
The integer inside the square brackets that follows the list is called
an index.
The first value in the list is at index 0, the second value is at index 1, the
third value is at index 2, and so on.
>>> 'The ' + spam[1] + ' ate the ' + spam[0] + '.‘
'The bat ate the cat.'
>>> spam=[1,2,3,4,5]
>>> 'I ate',spam[1],'Dosas today.‘
('I ate', 2, 'Dosas today.')
>>> 'I ate'+spam[1]+'Dosas today.’
Traceback (most recent call last): File "<stdin>", line 1, in <module>
TypeError:
can only concatenate str (not "int") to str
>>> 'I ate '+str(spam[1])+' Dosas today.‘
'I ate 2 Dosas today.'
Python will give you an IndexError error message if you use an index
that exceeds the number of values in your list value.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[10000]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
spam[10000]
IndexError: list index out of range
Indexes can be only integer values, not floats. The following example
will cause a TypeError error:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1]
'bat'
>>> spam[1.0]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
spam[1.0]
TypeError: list indices must be integers or slices, not float
>>> spam[int(1.0)]
'bat'
Lists can also contain other list values. The values in these lists of lists
can be accessed
Using multiple indexes, like so:
>>> spam=[['Hi','Hello'],[‘Will',‘Dave',‘Tom',‘Chris']]
>>> spam[0]
['Hi', 'Hello']
>>> spam[1]
[‘Will',‘Dave',‘Tom',‘Chris']
>>> spam[0][1]
'Hello’
>>> spam[1][2]
'Tom‘
>>> 'I want to tell '+str(spam[0][0])+' '+str(spam[1][0])
'I want to tell Hi Will'
Negative Indexes
While indexes start at 0 and go up, you can also use negative integers for
the index. The integer value -1 refers to the last index in a list, the value -
2 refers to the second-to-last index in a list, and so on.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
'elephant'
>>> spam[-3]
'bat'
>>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.'
'The elephant is afraid of the bat.'
A slice can get several values from a list, in the form of a new list. A
slice is typed between square brackets, like an index, but it has two integers
separated by a colon. Notice the difference between indexes and slices.
spam[2] is a list with an index (one integer).
spam[1:4] is a list with a slice (two integers).
In a slice, the first integer is the index where the slice starts. The
second integer is the index where the slice ends. A slice goes up to, but will
not include, the value at the second index. A slice evaluates to a new list
value.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat', 'rat']
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2]
['cat', 'bat']
>>> spam[1:]
['bat', 'rat', 'elephant']
>>> spam[:]
['cat', 'bat', 'rat', 'elephant']
>>> list1 =['Red','Green','Blue','Cyan', 'Magenta','Yellow','Black']
>>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']
#list1 is truncated to the end of the list
>>> list1[2:20] #second index is out of range
['Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']
>>> list1[7:2] #first index > second index
[ ] #results in an empty list
#return sublist from index 0 to 4
>>> list1[:5] #first index missing
['Red','Green','Blue','Cyan','Magenta']
>>> spam
['cat', 'aardvark', 'aardvark', 'elephant']
>>> spam[-1] = 12345
>>> spam
['cat', 'aardvark', 'aardvark', 12345]
Traversing a List
We can access each element of the list or traverse a list using a for loop or a
while loop.
Another way of accessing the elements of the list is using range() and len()
functions:
>>> for i in range(len(list1)):
print(list1[i])
Output:
Red
Green
Blue
Yellow
Black
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)
Output:
Enter the name of cat 1 (Or enter nothing to stop.):
Pooka
Enter the name of cat 2 (Or enter nothing to stop.):
eer
Enter the name of cat 3 (Or enter nothing to stop.):
Example:
Output:
The random module has a couple functions that accept lists for
arguments. The random.choice() function will return a randomly selected
item from the list.
>>> import random
>>> pets = ['Dog', 'Cat', 'Moose']
>>> random.choice(pets)
'Dog'
>>> random.choice(pets)
'Cat'
>>> random.choice(pets)
'Cat'
The random.shuffle() function will reorder the items in a list. This function
modifies the list in place, rather than returning a new list.
>>> import random
>>> people = ['Alice', 'Bob', 'Carol', 'David']
>>> random.shuffle(people)
>>> people
['Carol', 'David', 'Alice', 'Bob']
>>> random.shuffle(people)
>>> people
['Alice', 'David', 'Bob', 'Carol']
When assigning a value to a variable, you will frequently use the variable itself.
For example, after assigning 42 to the variable spam, you would increase the
value in spam by 1 with the following code:
>>> spam = 42
>>> spam = spam + 1
>>> spam
43
>>> spam = 42
>>> spam += 1
>>> spam
43
Methods
List values have an index() method that can be passed a value, and if that
value exists in the list, the index of the value is returned. If the value isn’t in
the list, then Python produces a ValueError error.
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3
>>> spam.index('howdy howdy howdy')
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
spam.index('howdy howdy howdy')
ValueError: 'howdy howdy howdy' is not in list
When there are duplicates of the value in the list, the index of its first
appearance is returned. Enter the following into the interactive shell, and
notice that index() returns 1, not 3:
>>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
>>> spam.index('Pooka')
1
The remove() method is passed the value to be removed from the list it is
called on.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('bat')
>>> spam
['cat', 'rat', 'elephant']
Attempting to delete a value that does not exist in the list will result in
a ValueError error.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('chicken')
If you need to quickly reverse the order of the items in a list, you can call
the reverse() list method.
>>> spam = ['cat', 'dog', 'moose']
>>> spam.reverse()
>>> spam
['moose', 'dog', 'cat']
import random
messages = ['It is certain',
'It is decidedly so',
'Yes definitely',
The above program gives us output randomly picking any string from the list.
The output changes whenever it is executed.
Returns maximum or
max() largest element of the >>> max(list1) 92
list
Lists aren’t the only data types that represent ordered sequences of
values.
For example, strings and lists are actually similar if you consider a string
to be a “list” of single text characters.
The Python sequence data types include lists, strings, range objects
returned by range(), and tuples.
Many of the things you can do with lists can also be done with strings and
other values of sequence types: indexing; slicing; and using them
with for loops, with len(), and with the in and not in operators.
>>> name = 'Zophie'
>>> name[0]
'Z'
>>> name[-2]
'i'
>>> name[0:4]
'Zoph'
>>> 'Zo' in name
True
>>> 'z' in name
False
>>> 'p' not in name
False
>>> for i in name:
... print('* * * ' + i + ' * * *')
* * * Z***
* * * o***
* * * p***
* * * h***
* * * i***
* * * e***
A list value is a mutable data type: it can have values added, removed, or
changed. However, a string is immutable: it cannot be changed.
>>> name = 'Zophie a cat'
>>> name[7] = 'the'
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
name[7] = 'the'
TypeError: 'str' object does not support item assignment
The proper way to “mutate” a string is to use slicing and concatenation to
build a new string by copying from parts of the old string.
>>> name='My name Nisha'
>>> newname=name[0:7]+‘ is '+name[8:13]
‘My name is Nisha’
Although a list value is mutable.
>>> eggs = [1, 2, 3]
>>> eggs = [4, 5, 6]
>>> eggs
[4, 5, 6]
The list value in eggs isn’t being changed here; rather, an entirely new and
different list value ([4, 5, 6]) is overwriting the old list value ([1, 2, 3])
Nested Lists
Copying Lists:
Given a list, the simplest way to make a copy of the list is to assign it to
another list.
>>> list1 = [1,2,3]
>>> list2 = list1
>>> list1
[1, 2, 3]
>>> list2
[1, 2, 3]
The statement list2 = list1 does not create a new list.
Rather, it just makes list1 and list2 refer to the same list object.
Here list2 actually becomes an alias of list1.
Therefore, any changes made to either of them will be reflected in the
other list.
>>> list1.append(10)
>>> list1
[1, 2, 3, 10]
>>> list2
[1, 2, 3, 10]
We can also create a copy or clone of the list as a distinct object by three
methods.
The first method uses slicing, the second method uses built-in function
list() and the third method uses copy() function of python library copy.
Method 1
We can slice our original list and store it into a new variable as follows:
newList = oldList[:]
>>> list1 = [1,2,3,4,5]
>>> list2 = list1[:]
>>> list2
[1, 2, 3, 4, 5]
Method 2
We can use the built-in function list() as follows:
newList = list(oldList)
def increment(list2):
for i in range(0,len(list2)):
list2[i] += 5
print('Reference of list Inside Function',id(list2))
list1 = [10,20,30,40,50] #Create a list
print("The list before the function call")
print(list1)
increment(list1) #list1 is passed as parameter to function
print("The list after the function call")
print(list1)
Output:
The list before the function call
[10, 20, 30, 40, 50]
Reference of list Inside Function 140290458650304
The list after the function call
[15, 25, 35, 45, 55]
def increment(list2):
print("\nID of list inside function before assignment:",id(list2))
list2 = [15,25,35,45,55] #List2 assigned a new list
print("ID of list changes inside function after assignment:",id(list2))
print("The list inside the function after assignment is:")
print(list2)
#end of function
list1 = [10,20,30,40,50] #Create a list
print("ID of list before function call:",id(list1))
print("The list before function call:")
print(list1)
increment(list1) #list1 passed as parameter to function
print('\nID of list after function call:',id(list1))
print("The list after the function call:")
print(list1)
Output:
ID of list before function call: 140642743551680
The list before function call:
[10, 20, 30, 40, 50]
List Manipulation:
Write a menu driven program to perform various list operations, such
as:
• Append an element
• Insert an element
myList = [22,4,16,38,13]
choice = 0
while True:
print("The list 'myList' has the following elements", myList)
print("\nL I S T O P E R A T I O N S")
print(" 1. Append an element")
print(" 2. Insert an element at the desired position")
print(" 3. Append a list to the given list")
print(" 4. Modify an existing element")
print(" 5. Delete an existing element by its position")
print(" 6. Delete an existing element by its value")
print(" 7. Sort the list in ascending order")
print(" 8. Sort the list in descending order")
print(" 9. Display the list")
print(" 10. Exit")
choice = int(input("ENTER YOUR CHOICE (1-10): "))
if choice == 1:
element = int(input("Enter the element to be appended: "))
myList.append(element)
print("The element has been appended\n")
elif choice == 2:
element = int(input("Enter the element to be inserted: "))
pos = int(input("Enter the position:"))
myList.insert(pos,element)
print("The element has been inserted\n")
elif choice == 3:
newList = eval(input( "Enter the elements separated by commas"))
myList.extend(list(newList))
print("The list has been appended\n")
elif choice == 4:
i = int(input("Enter the position of the element to be modified: "))
if i < len(myList):
newElement = int(input("Enter the new element: "))
oldElement = myList[i]
myList[i] = newElement
print("The element",oldElement,"has been modified\n")
else:
print("Position of the element is more than the length of list")
elif choice == 5:
i = int(input("Enter the position of the element to be deleted: "))
if i < len(myList):
element = myList.pop(i)
print("The element",element,"has been deleted\n")
else:
print("\nPosition of the element is more than the length of list")
elif choice == 6:
element = int(input("\nEnter the element to be deleted: "))
if element in myList:
myList.remove(element)
print("\nThe element",element,"has been deleted\n")
else:
print("\nElement",element,"is not present in the list")
elif choice == 7:
myList.sort()
print("\nThe list has been sorted")
elif choice == 8:
myList.sort(reverse = True)
print("\nThe list has been sorted in reverse order")
elif choice == 9:
print("\nThe list is:", myList)
elif choice == 10:
break
else:
print("Choice is not valid")
print("\n\nPress any key to continue..............")
ch = input()
Output:
The list 'myList' has the following elements [22, 4, 16, 38, 13]
LISTOPERATIONS
1. Append an element
2. Insert an element at the desired position
3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element by its position
6. Delete an existing element by its value
7. Sort the list in ascending order
8. Sort the list in descending order
9. Display the list
10. Exit
ENTER YOUR CHOICE (1-10): 7
LISTOPERATIONS
1. Append an element
2. Insert an element at the desired position
3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element by its position
6. Delete an existing element by its value
7. Sort the list in ascending order
8. Sort the list in descending order
9. Display the list
10. Exit
ENTER YOUR CHOICE (1-10): 8
LISTOPERATIONS
1. Append an element
def computeAverage(list1,n):
total = 0
for marks in list1:
total = total + marks
average = total / n
return average
list1 = []
print("How many students marks you want to enter: ")
n = int(input())
for i in range(0,n):
print("Enter marks of student",(i+1),":")
marks = int(input())
list1.append(marks)
average = computeAverage(list1,n)
print("Average marks of",n,"students is:",average)
Output:
How many students marks you want to enter:
5
Enter marks of student 1 :
45
Enter marks of student 2 :
89
def linearSearch(num,list1):
for i in range(0,len(list1)):
if list1[i] == num: #num is present
return i #return the position
return None #num is not present in the list
list1 = [] #Create an empty list
print("How many numbers do you want to enter in the list: ")
maximum = int(input())
print("Enter a list of numbers: ")
for i in range(0,maximum):
n = int(input())
list1.append(n) #append numbers to the list
num = int(input("Enter the number to be searched: "))
result = linearSearch(num,list1)
if result is None:
print("Number",num,"is not present in the list")
else:
print("Number",num,"is present at",result + 1, "position")
Output:
How many numbers do you want to enter in the list:
5
Enter a list of numbers:
23
567
12
89
324
Enter the number to be searched: 12
Number 12 is present at 3 position
Tuple is Immutable
Tuple is an immutable data type. It means that the elements of a tuple
cannot be changed after it has been created. An attempt to do this would
lead to an error.
>>> tuple1 = (1,2,3,4,5)
>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment
However an element of a tuple may be of mutable type, e.g., a list.
#4th element of the tuple2 is a list
>>> tuple2 = (1,2,3,[8,9])
#modify the list element of the tuple2
>>> tuple2[3][1] = 10
#modification is reflected in tuple2
>>> tuple2
(1, 2, 3, [8, 10])
Tuple Operations
Concatenation
Python allows us to join tuples using concatenation operator depicted
by symbol +. We can also create a new tuple which contains the result
of this concatenation operation.
>>> tuple1 = (1,3,5,7,9)
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
,'Black')
>>> tuple6
(1, 2, 3, 4, 5, 6)
>>> tuple6
(1, 2, 3, 4, 5, 6, 7, 8, 9)
Repetition
Repetition operation is depicted by the symbol *. It is used to repeat
elements of a tuple. We can repeat the tuple elements. The repetition
operator requires the first operand to be a tuple and the second operand
to be an integer only.
>>> tuple1 = ('Hello','World')
>>> tuple1 * 3
>>> tuple2 * 4
Membership
The in operator checks if the element is present in the tuple and
returns True, else it returns False.
>>> tuple1 = ('Red','Green','Blue')
The not in operator returns True if the element is not present in the
tuple, else it returns False.
>>> tuple1 = ('Red','Green','Blue')
Slicing
Like string and list, slicing can be applied to tuples also.
#tuple1 is a tuple
>>> tuple1[0:len(tuple1)]
>>> tuple1[:5]
>>> tuple1[2:]
#step size 2
>>> tuple1[::-1]
TUPLE ASSIGNMENT
Assignment of tuple is a useful feature in Python. It allows a
tuple of variables on the left side of the assignment operator to be
assigned respective values from a tuple on the right side. The
number of variables on the left should be same as the number of
elements in the tuple.
Example
>>> print(num1) 10
>>> print(num2) 20
>>> rollNo 40
>>> print(num4) 25
print("First Number:",num1)
print("Second Number:",num2)
(num1,num2) = (num2,num1)
print("First Number:",num1)
print("Second Number:",num2)
Output:
First Number: 10
Second Number: 20
First Number: 20
Second Number: 10
Write a program to input n numbers from the user. Store these numbers
in a tuple. Print the maximum and minimum number from this tuple.
numbers = tuple()
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n):
num = int(input())
numbers = numbers +(num,)
print('\nThe numbers in the tuple are:')
print(numbers)
print("\nThe maximum number is:")
print(max(numbers))
print("The minimum number is:")
print(min(numbers))
Output:
How many numbers you want to enter?: 5
1
2
3
4
5
References
Technically, variables are storing references to the computer memory
locations where the values are stored.
>>> spam = 42
>>> cheese = spam
>>> spam = 100
>>> spam
100
>>> cheese
42
When you assign 42 to the spam variable, you are actually creating
the 42 value in the computer’s memory and storing a reference to it in the
spam variable. When you copy the value in spam and assign it to the
variable cheese, you are actually copying the reference. Both
the spam and cheese variables refer to the 42 value in the computer’s
memory. When you later change the value in spam to 100, you’re creating a
new 100 value and storing a reference to it in spam. This doesn’t affect the
value in cheese. Integers are immutable values that don’t change; changing
the spam variable is actually making it refer to a completely different value in
memory.
But lists don’t work this way, because list values can change; that is, lists
are mutable.
>>> spam = [0, 1, 2, 3, 4, 5]
>>> cheese = spam # The reference is being copied, not the list.
>>> cheese[1] = 'Hello!' # This changes the list value.
>>> spam
[0, 'Hello!', 2, 3, 4, 5]
>>> cheese # The cheese variable refers to the same list.
[0, 'Hello!', 2, 3, 4, 5]
Passing References
References are particularly important for understanding how arguments
get passed to functions. When a function is called, the values of the
arguments are copied to the parameter variables. For lists, this means a copy
of the reference is used for the parameter.
Example:
def eggs(someParameter):
someParameter.append('Hello')
spam = [1, 2, 3]
eggs(spam)
print(spam)
Example:
Predict data about Friend’s birthday:
birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday
print('Birthday database updated.')
Output:
Enter a name: (blank to quit)
Alex
I do not have birthday information for Alex
What is their birthday?
June 21
Birthday database updated.
Enter a name: (blank to quit)
Alex
June 21 is the birthday of Alex
Enter a name: (blank to quit)
red
42
>>> for k in spam.keys():
... print(k)
color
age
>>> for i in spam.items():
... print(i)
('color', 'red')
('age', 42)
>>> spam = {'color': 'red', 'age': 42}
>>> spam.keys()
dict_keys(['color', 'age'])
>>> list(spam.keys())
['color', 'age']
The list(spam.keys()) line takes the dict_keys value returned
from keys() and passes it to list(), which then returns a list value of ['color',
'age'].
You can also use the multiple assignment trick in a for loop to assign the
key and value to separate variables.
>>> spam = {'color': 'red', 'age': 42}
>>> for k, v in spam.items():
... print('Key: ' + k + ' Value: ' + str(v))
Pretty Printing
If you import the pprint module into your programs, you’ll have access
to the pprint() and pformat() functions that will “pretty print” a dictionary’s
values. This is helpful when you want a cleaner display of the items in a
dictionary than what print() provides.
import pprint
message = 'Hello World!'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
Output:
{' ': 1, '!': 1, 'H': 1, 'W': 1, 'd': 1, 'e': 1, 'l': 3, 'o': 2, 'r': 1}
A Tic_Tac_Toe Board
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M':
' ', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on which space?')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'
printBoard(theBoard)
Output:
Number of things being brought:
- Apples 7
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1
employees = {}
while True:
name = input("Enter employee name (or 'quit' to exit): ")
if name == "quit":
break
emp_id = input("Enter employee ID: ")
salary = input("Enter employee salary: ")
employees[name] = {"id": emp_id, "salary": salary}
while True:
lookup_name = input("Enter the name of the employee to look up: ")
if lookup_name == "end":
break
if lookup_name in employees:
emp_id = employees[lookup_name]["id"]
salary = employees[lookup_name]["salary"]
print(f"Employee ID: {emp_id}")
capitals={}
n = int(input("Enter the number of cities to add:"))
for i in range(n):
key=input("Enter country name:")
value=input("Enter its capital:")
capitals[key]=value
sorted_capitals = dict(sorted(capitals.items()))
for country, capital in sorted_capitals.items():
print("The capital of {} is {}".format(country, capital))
Write a Python program to accept ‘n’ numbers from the user. Find the
sum of all even numbers and the product of all odd numbers in the
entered list.
list=[]
n=int(input('Enter the number of elements in the list: '))
for i in range(n):
val=int(input('Enter the value: '))
list.append(val)
a=0
b=1
for i in range(n+1):
if i%2==0:
a+=i
else:
b*=i
print("Sum of even numbers=",a)
print("Product of odd numers=",b)
Output:
Enter the number of elements in the list: 5
Enter the value: 1
Enter the value: 2
Enter the value: 3
Enter the value: 4
Enter the value: 5
Sum of even numbers= 6
Product of odd numers= 15
Read N numbers from the console and create a list. Develop a program
to print mean, variance and standard deviation with suitable messages.
Output:
Enter the number of elemnts in your list: 5
Enter the value: 1
Enter the value: 2
Enter the value: 3
student_db = {}
def search_student_by_usn(usn):
return student_db.get(usn, "Student not found.")
def delete_student_by_name(name):
usns_to_delete = [usn for usn, details in student_db.items() if details["Name"]
== name]
for usn in usns_to_delete:
del student_db[usn]
def generate_report():
report = {}
for usn, details in student_db.items():
avg_marks = (details["Marks1"] + details["Marks2"] + details["Marks3"]) / 3
if avg_marks > 70:
report[usn] = details
return report
def main():
while True:
print("\nStudent Database Menu:")
print("1. Add Student")
print("2. Update Student")
print("3. Search Student by USN")
print("4. Delete Student by Name")
print("5. Generate Report (Avg Marks > 70%)")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
usn = input("Enter USN: ")
name = input("Enter Name: ")
gender = input("Enter Gender: ")
marks1 = float(input("Enter Marks1: "))
marks2 = float(input("Enter Marks2: "))
marks3 = float(input("Enter Marks3: "))
add_student(usn, name, gender, marks1, marks2, marks3)
print(f"Student {name} added successfully.")
if __name__ == "__main__":
main()
Write a program to enter names of employees and their salaries as input and
store them in a dictionary.
count = 1
employee = dict() #create an empty dictionary
while count <= num:
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k,'\t\t',employee[k])
Output:
Enter the number of employees to be stored: 5
Enter the name of the Employee: 'Tarun'
Enter the salary: 12000
Enter the name of the Employee: 'Amina'
Enter the salary: 34000
Enter the name of the Employee: 'Joseph'
Enter the salary: 24000
Enter the name of the Employee: 'Rahul'
Enter the salary: 30000
Enter the name of the Employee: 'Zoya'
Enter the salary: 25000
EMPLOYEE_NAME SALARY
'Tarun' 12000
'Amina' 34000
'Joseph' 24000
'Rahul' 30000
'Zoya' 25000
****End****
Module 2
Data Structures: Lists: The List Data Type, Working with Lists Strings: Manipulating Strings,
Working with Strings, Useful String Methods Tuples and Dictionaries, basics Using Data
Structures to Model Real-World Things, Manipulating Strings.
>>> print(list3)
[100, 23.5, 'Hello']
#list4 is the list of lists called nested list
>>> list4 =[['Physics',101],['Chemistry',202], ['Maths',303]]
>>> print(list4)
[['Physics', 101], ['Chemistry', 202], ['Maths', 303]]
Say you have the list ['cat', 'bat', 'rat', 'elephant'] stored in a variable
named spam.
The Python code spam[0] would evaluate to 'cat', and spam[1] would
evaluate to 'bat', and so on.
The integer inside the square brackets that follows the list is called
an index.
The first value in the list is at index 0, the second value is at index 1, the
third value is at index 2, and so on.
>>> 'The ' + spam[1] + ' ate the ' + spam[0] + '.‘
'The bat ate the cat.'
>>> spam=[1,2,3,4,5]
>>> 'I ate',spam[1],'Dosas today.‘
('I ate', 2, 'Dosas today.')
>>> 'I ate'+spam[1]+'Dosas today.’
Traceback (most recent call last): File "<stdin>", line 1, in <module>
TypeError:
can only concatenate str (not "int") to str
>>> 'I ate '+str(spam[1])+' Dosas today.‘
'I ate 2 Dosas today.'
Python will give you an IndexError error message if you use an index
that exceeds the number of values in your list value.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[10000]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
spam[10000]
IndexError: list index out of range
Indexes can be only integer values, not floats. The following example
will cause a TypeError error:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1]
'bat'
>>> spam[1.0]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
spam[1.0]
TypeError: list indices must be integers or slices, not float
>>> spam[int(1.0)]
'bat'
Lists can also contain other list values. The values in these lists of lists
can be accessed
Using multiple indexes, like so:
>>> spam=[['Hi','Hello'],[‘Will',‘Dave',‘Tom',‘Chris']]
>>> spam[0]
['Hi', 'Hello']
>>> spam[1]
[‘Will',‘Dave',‘Tom',‘Chris']
>>> spam[0][1]
'Hello’
>>> spam[1][2]
'Tom‘
>>> 'I want to tell '+str(spam[0][0])+' '+str(spam[1][0])
'I want to tell Hi Will'
Negative Indexes
While indexes start at 0 and go up, you can also use negative integers for
the index. The integer value -1 refers to the last index in a list, the value -
2 refers to the second-to-last index in a list, and so on.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
'elephant'
>>> spam[-3]
'bat'
>>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.'
'The elephant is afraid of the bat.'
A slice can get several values from a list, in the form of a new list. A
slice is typed between square brackets, like an index, but it has two integers
separated by a colon. Notice the difference between indexes and slices.
spam[2] is a list with an index (one integer).
spam[1:4] is a list with a slice (two integers).
In a slice, the first integer is the index where the slice starts. The
second integer is the index where the slice ends. A slice goes up to, but will
not include, the value at the second index. A slice evaluates to a new list
value.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat', 'rat']
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2]
['cat', 'bat']
>>> spam[1:]
['bat', 'rat', 'elephant']
>>> spam[:]
['cat', 'bat', 'rat', 'elephant']
>>> list1 =['Red','Green','Blue','Cyan', 'Magenta','Yellow','Black']
>>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']
#list1 is truncated to the end of the list
>>> list1[2:20] #second index is out of range
['Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']
>>> list1[7:2] #first index > second index
[ ] #results in an empty list
#return sublist from index 0 to 4
>>> list1[:5] #first index missing
['Red','Green','Blue','Cyan','Magenta']
>>> spam
['cat', 'aardvark', 'aardvark', 'elephant']
>>> spam[-1] = 12345
>>> spam
['cat', 'aardvark', 'aardvark', 12345]
Traversing a List
We can access each element of the list or traverse a list using a for loop or a
while loop.
Another way of accessing the elements of the list is using range() and len()
functions:
>>> for i in range(len(list1)):
print(list1[i])
Output:
Red
Green
Blue
Yellow
Black
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)
Output:
Enter the name of cat 1 (Or enter nothing to stop.):
Pooka
Enter the name of cat 2 (Or enter nothing to stop.):
eer
Enter the name of cat 3 (Or enter nothing to stop.):
Example:
Output:
The random module has a couple functions that accept lists for
arguments. The random.choice() function will return a randomly selected
item from the list.
>>> import random
>>> pets = ['Dog', 'Cat', 'Moose']
>>> random.choice(pets)
'Dog'
>>> random.choice(pets)
'Cat'
>>> random.choice(pets)
'Cat'
The random.shuffle() function will reorder the items in a list. This function
modifies the list in place, rather than returning a new list.
>>> import random
>>> people = ['Alice', 'Bob', 'Carol', 'David']
>>> random.shuffle(people)
>>> people
['Carol', 'David', 'Alice', 'Bob']
>>> random.shuffle(people)
>>> people
['Alice', 'David', 'Bob', 'Carol']
When assigning a value to a variable, you will frequently use the variable itself.
For example, after assigning 42 to the variable spam, you would increase the
value in spam by 1 with the following code:
>>> spam = 42
>>> spam = spam + 1
>>> spam
43
>>> spam = 42
>>> spam += 1
>>> spam
43
Methods
List values have an index() method that can be passed a value, and if that
value exists in the list, the index of the value is returned. If the value isn’t in
the list, then Python produces a ValueError error.
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3
>>> spam.index('howdy howdy howdy')
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
spam.index('howdy howdy howdy')
ValueError: 'howdy howdy howdy' is not in list
When there are duplicates of the value in the list, the index of its first
appearance is returned. Enter the following into the interactive shell, and
notice that index() returns 1, not 3:
>>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
>>> spam.index('Pooka')
1
The remove() method is passed the value to be removed from the list it is
called on.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('bat')
>>> spam
['cat', 'rat', 'elephant']
Attempting to delete a value that does not exist in the list will result in
a ValueError error.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('chicken')
If you need to quickly reverse the order of the items in a list, you can call
the reverse() list method.
>>> spam = ['cat', 'dog', 'moose']
>>> spam.reverse()
>>> spam
['moose', 'dog', 'cat']
import random
messages = ['It is certain',
'It is decidedly so',
'Yes definitely',
The above program gives us output randomly picking any string from the list.
The output changes whenever it is executed.
Returns maximum or
max() largest element of the >>> max(list1) 92
list
Lists aren’t the only data types that represent ordered sequences of
values.
For example, strings and lists are actually similar if you consider a string
to be a “list” of single text characters.
The Python sequence data types include lists, strings, range objects
returned by range(), and tuples.
Many of the things you can do with lists can also be done with strings and
other values of sequence types: indexing; slicing; and using them
with for loops, with len(), and with the in and not in operators.
>>> name = 'Zophie'
>>> name[0]
'Z'
>>> name[-2]
'i'
>>> name[0:4]
'Zoph'
>>> 'Zo' in name
True
>>> 'z' in name
False
>>> 'p' not in name
False
>>> for i in name:
... print('* * * ' + i + ' * * *')
* * * Z***
* * * o***
* * * p***
* * * h***
* * * i***
* * * e***
A list value is a mutable data type: it can have values added, removed, or
changed. However, a string is immutable: it cannot be changed.
>>> name = 'Zophie a cat'
>>> name[7] = 'the'
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
name[7] = 'the'
TypeError: 'str' object does not support item assignment
The proper way to “mutate” a string is to use slicing and concatenation to
build a new string by copying from parts of the old string.
>>> name='My name Nisha'
>>> newname=name[0:7]+‘ is '+name[8:13]
‘My name is Nisha’
Although a list value is mutable.
>>> eggs = [1, 2, 3]
>>> eggs = [4, 5, 6]
>>> eggs
[4, 5, 6]
The list value in eggs isn’t being changed here; rather, an entirely new and
different list value ([4, 5, 6]) is overwriting the old list value ([1, 2, 3])
Nested Lists
Copying Lists:
Given a list, the simplest way to make a copy of the list is to assign it to
another list.
>>> list1 = [1,2,3]
>>> list2 = list1
>>> list1
[1, 2, 3]
>>> list2
[1, 2, 3]
The statement list2 = list1 does not create a new list.
Rather, it just makes list1 and list2 refer to the same list object.
Here list2 actually becomes an alias of list1.
Therefore, any changes made to either of them will be reflected in the
other list.
>>> list1.append(10)
>>> list1
[1, 2, 3, 10]
>>> list2
[1, 2, 3, 10]
We can also create a copy or clone of the list as a distinct object by three
methods.
The first method uses slicing, the second method uses built-in function
list() and the third method uses copy() function of python library copy.
Method 1
We can slice our original list and store it into a new variable as follows:
newList = oldList[:]
>>> list1 = [1,2,3,4,5]
>>> list2 = list1[:]
>>> list2
[1, 2, 3, 4, 5]
Method 2
We can use the built-in function list() as follows:
newList = list(oldList)
def increment(list2):
for i in range(0,len(list2)):
list2[i] += 5
print('Reference of list Inside Function',id(list2))
list1 = [10,20,30,40,50] #Create a list
print("The list before the function call")
print(list1)
increment(list1) #list1 is passed as parameter to function
print("The list after the function call")
print(list1)
Output:
The list before the function call
[10, 20, 30, 40, 50]
Reference of list Inside Function 140290458650304
The list after the function call
[15, 25, 35, 45, 55]
def increment(list2):
print("\nID of list inside function before assignment:",id(list2))
list2 = [15,25,35,45,55] #List2 assigned a new list
print("ID of list changes inside function after assignment:",id(list2))
print("The list inside the function after assignment is:")
print(list2)
#end of function
list1 = [10,20,30,40,50] #Create a list
print("ID of list before function call:",id(list1))
print("The list before function call:")
print(list1)
increment(list1) #list1 passed as parameter to function
print('\nID of list after function call:',id(list1))
print("The list after the function call:")
print(list1)
Output:
ID of list before function call: 140642743551680
The list before function call:
[10, 20, 30, 40, 50]
List Manipulation:
Write a menu driven program to perform various list operations, such
as:
• Append an element
• Insert an element
myList = [22,4,16,38,13]
choice = 0
while True:
print("The list 'myList' has the following elements", myList)
print("\nL I S T O P E R A T I O N S")
print(" 1. Append an element")
print(" 2. Insert an element at the desired position")
print(" 3. Append a list to the given list")
print(" 4. Modify an existing element")
print(" 5. Delete an existing element by its position")
print(" 6. Delete an existing element by its value")
print(" 7. Sort the list in ascending order")
print(" 8. Sort the list in descending order")
print(" 9. Display the list")
print(" 10. Exit")
choice = int(input("ENTER YOUR CHOICE (1-10): "))
if choice == 1:
element = int(input("Enter the element to be appended: "))
myList.append(element)
print("The element has been appended\n")
elif choice == 2:
element = int(input("Enter the element to be inserted: "))
pos = int(input("Enter the position:"))
myList.insert(pos,element)
print("The element has been inserted\n")
elif choice == 3:
newList = eval(input( "Enter the elements separated by commas"))
myList.extend(list(newList))
print("The list has been appended\n")
elif choice == 4:
i = int(input("Enter the position of the element to be modified: "))
if i < len(myList):
newElement = int(input("Enter the new element: "))
oldElement = myList[i]
myList[i] = newElement
print("The element",oldElement,"has been modified\n")
else:
print("Position of the element is more than the length of list")
elif choice == 5:
i = int(input("Enter the position of the element to be deleted: "))
if i < len(myList):
element = myList.pop(i)
print("The element",element,"has been deleted\n")
else:
print("\nPosition of the element is more than the length of list")
elif choice == 6:
element = int(input("\nEnter the element to be deleted: "))
if element in myList:
myList.remove(element)
print("\nThe element",element,"has been deleted\n")
else:
print("\nElement",element,"is not present in the list")
elif choice == 7:
myList.sort()
print("\nThe list has been sorted")
elif choice == 8:
myList.sort(reverse = True)
print("\nThe list has been sorted in reverse order")
elif choice == 9:
print("\nThe list is:", myList)
elif choice == 10:
break
else:
print("Choice is not valid")
print("\n\nPress any key to continue..............")
ch = input()
Output:
The list 'myList' has the following elements [22, 4, 16, 38, 13]
LISTOPERATIONS
1. Append an element
2. Insert an element at the desired position
3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element by its position
6. Delete an existing element by its value
7. Sort the list in ascending order
8. Sort the list in descending order
9. Display the list
10. Exit
ENTER YOUR CHOICE (1-10): 7
LISTOPERATIONS
1. Append an element
2. Insert an element at the desired position
3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element by its position
6. Delete an existing element by its value
7. Sort the list in ascending order
8. Sort the list in descending order
9. Display the list
10. Exit
ENTER YOUR CHOICE (1-10): 8
LISTOPERATIONS
1. Append an element
def computeAverage(list1,n):
total = 0
for marks in list1:
total = total + marks
average = total / n
return average
list1 = []
print("How many students marks you want to enter: ")
n = int(input())
for i in range(0,n):
print("Enter marks of student",(i+1),":")
marks = int(input())
list1.append(marks)
average = computeAverage(list1,n)
print("Average marks of",n,"students is:",average)
Output:
How many students marks you want to enter:
5
Enter marks of student 1 :
45
Enter marks of student 2 :
89
def linearSearch(num,list1):
for i in range(0,len(list1)):
if list1[i] == num: #num is present
return i #return the position
return None #num is not present in the list
list1 = [] #Create an empty list
print("How many numbers do you want to enter in the list: ")
maximum = int(input())
print("Enter a list of numbers: ")
for i in range(0,maximum):
n = int(input())
list1.append(n) #append numbers to the list
num = int(input("Enter the number to be searched: "))
result = linearSearch(num,list1)
if result is None:
print("Number",num,"is not present in the list")
else:
print("Number",num,"is present at",result + 1, "position")
Output:
How many numbers do you want to enter in the list:
5
Enter a list of numbers:
23
567
12
89
324
Enter the number to be searched: 12
Number 12 is present at 3 position
Tuple is Immutable
Tuple is an immutable data type. It means that the elements of a tuple
cannot be changed after it has been created. An attempt to do this would
lead to an error.
>>> tuple1 = (1,2,3,4,5)
>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment
However an element of a tuple may be of mutable type, e.g., a list.
#4th element of the tuple2 is a list
>>> tuple2 = (1,2,3,[8,9])
#modify the list element of the tuple2
>>> tuple2[3][1] = 10
#modification is reflected in tuple2
>>> tuple2
(1, 2, 3, [8, 10])
Tuple Operations
Concatenation
Python allows us to join tuples using concatenation operator depicted
by symbol +. We can also create a new tuple which contains the result
of this concatenation operation.
>>> tuple1 = (1,3,5,7,9)
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
,'Black')
>>> tuple6
(1, 2, 3, 4, 5, 6)
>>> tuple6
(1, 2, 3, 4, 5, 6, 7, 8, 9)
Repetition
Repetition operation is depicted by the symbol *. It is used to repeat
elements of a tuple. We can repeat the tuple elements. The repetition
operator requires the first operand to be a tuple and the second operand
to be an integer only.
>>> tuple1 = ('Hello','World')
>>> tuple1 * 3
>>> tuple2 * 4
Membership
The in operator checks if the element is present in the tuple and
returns True, else it returns False.
>>> tuple1 = ('Red','Green','Blue')
The not in operator returns True if the element is not present in the
tuple, else it returns False.
>>> tuple1 = ('Red','Green','Blue')
Slicing
Like string and list, slicing can be applied to tuples also.
#tuple1 is a tuple
>>> tuple1[0:len(tuple1)]
>>> tuple1[:5]
>>> tuple1[2:]
#step size 2
>>> tuple1[::-1]
TUPLE ASSIGNMENT
Assignment of tuple is a useful feature in Python. It allows a
tuple of variables on the left side of the assignment operator to be
assigned respective values from a tuple on the right side. The
number of variables on the left should be same as the number of
elements in the tuple.
Example
>>> print(num1) 10
>>> print(num2) 20
>>> rollNo 40
>>> print(num4) 25
print("First Number:",num1)
print("Second Number:",num2)
(num1,num2) = (num2,num1)
print("First Number:",num1)
print("Second Number:",num2)
Output:
First Number: 10
Second Number: 20
First Number: 20
Second Number: 10
Write a program to input n numbers from the user. Store these numbers
in a tuple. Print the maximum and minimum number from this tuple.
numbers = tuple()
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n):
num = int(input())
numbers = numbers +(num,)
print('\nThe numbers in the tuple are:')
print(numbers)
print("\nThe maximum number is:")
print(max(numbers))
print("The minimum number is:")
print(min(numbers))
Output:
How many numbers you want to enter?: 5
1
2
3
4
5
References
Technically, variables are storing references to the computer memory
locations where the values are stored.
>>> spam = 42
>>> cheese = spam
>>> spam = 100
>>> spam
100
>>> cheese
42
When you assign 42 to the spam variable, you are actually creating
the 42 value in the computer’s memory and storing a reference to it in the
spam variable. When you copy the value in spam and assign it to the
variable cheese, you are actually copying the reference. Both
the spam and cheese variables refer to the 42 value in the computer’s
memory. When you later change the value in spam to 100, you’re creating a
new 100 value and storing a reference to it in spam. This doesn’t affect the
value in cheese. Integers are immutable values that don’t change; changing
the spam variable is actually making it refer to a completely different value in
memory.
But lists don’t work this way, because list values can change; that is, lists
are mutable.
>>> spam = [0, 1, 2, 3, 4, 5]
>>> cheese = spam # The reference is being copied, not the list.
>>> cheese[1] = 'Hello!' # This changes the list value.
>>> spam
[0, 'Hello!', 2, 3, 4, 5]
>>> cheese # The cheese variable refers to the same list.
[0, 'Hello!', 2, 3, 4, 5]
Passing References
References are particularly important for understanding how arguments
get passed to functions. When a function is called, the values of the
arguments are copied to the parameter variables. For lists, this means a copy
of the reference is used for the parameter.
Example:
def eggs(someParameter):
someParameter.append('Hello')
spam = [1, 2, 3]
eggs(spam)
print(spam)
Example:
Predict data about Friend’s birthday:
birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday
print('Birthday database updated.')
Output:
Enter a name: (blank to quit)
Alex
I do not have birthday information for Alex
What is their birthday?
June 21
Birthday database updated.
Enter a name: (blank to quit)
Alex
June 21 is the birthday of Alex
Enter a name: (blank to quit)
red
42
>>> for k in spam.keys():
... print(k)
color
age
>>> for i in spam.items():
... print(i)
('color', 'red')
('age', 42)
>>> spam = {'color': 'red', 'age': 42}
>>> spam.keys()
dict_keys(['color', 'age'])
>>> list(spam.keys())
['color', 'age']
The list(spam.keys()) line takes the dict_keys value returned
from keys() and passes it to list(), which then returns a list value of ['color',
'age'].
You can also use the multiple assignment trick in a for loop to assign the
key and value to separate variables.
>>> spam = {'color': 'red', 'age': 42}
>>> for k, v in spam.items():
... print('Key: ' + k + ' Value: ' + str(v))
Pretty Printing
If you import the pprint module into your programs, you’ll have access
to the pprint() and pformat() functions that will “pretty print” a dictionary’s
values. This is helpful when you want a cleaner display of the items in a
dictionary than what print() provides.
import pprint
message = 'Hello World!'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
Output:
{' ': 1, '!': 1, 'H': 1, 'W': 1, 'd': 1, 'e': 1, 'l': 3, 'o': 2, 'r': 1}
A Tic_Tac_Toe Board
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M':
' ', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on which space?')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'
printBoard(theBoard)
Output:
Number of things being brought:
- Apples 7
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1
employees = {}
while True:
name = input("Enter employee name (or 'quit' to exit): ")
if name == "quit":
break
emp_id = input("Enter employee ID: ")
salary = input("Enter employee salary: ")
employees[name] = {"id": emp_id, "salary": salary}
while True:
lookup_name = input("Enter the name of the employee to look up: ")
if lookup_name == "end":
break
if lookup_name in employees:
emp_id = employees[lookup_name]["id"]
salary = employees[lookup_name]["salary"]
print(f"Employee ID: {emp_id}")
capitals={}
n = int(input("Enter the number of cities to add:"))
for i in range(n):
key=input("Enter country name:")
value=input("Enter its capital:")
capitals[key]=value
sorted_capitals = dict(sorted(capitals.items()))
for country, capital in sorted_capitals.items():
print("The capital of {} is {}".format(country, capital))
Write a Python program to accept ‘n’ numbers from the user. Find the
sum of all even numbers and the product of all odd numbers in the
entered list.
list=[]
n=int(input('Enter the number of elements in the list: '))
for i in range(n):
val=int(input('Enter the value: '))
list.append(val)
a=0
b=1
for i in range(n+1):
if i%2==0:
a+=i
else:
b*=i
print("Sum of even numbers=",a)
print("Product of odd numers=",b)
Output:
Enter the number of elements in the list: 5
Enter the value: 1
Enter the value: 2
Enter the value: 3
Enter the value: 4
Enter the value: 5
Sum of even numbers= 6
Product of odd numers= 15
Read N numbers from the console and create a list. Develop a program
to print mean, variance and standard deviation with suitable messages.
Output:
Enter the number of elemnts in your list: 5
Enter the value: 1
Enter the value: 2
Enter the value: 3
student_db = {}
def search_student_by_usn(usn):
return student_db.get(usn, "Student not found.")
def delete_student_by_name(name):
usns_to_delete = [usn for usn, details in student_db.items() if details["Name"]
== name]
for usn in usns_to_delete:
del student_db[usn]
def generate_report():
report = {}
for usn, details in student_db.items():
avg_marks = (details["Marks1"] + details["Marks2"] + details["Marks3"]) / 3
if avg_marks > 70:
report[usn] = details
return report
def main():
while True:
print("\nStudent Database Menu:")
print("1. Add Student")
print("2. Update Student")
print("3. Search Student by USN")
print("4. Delete Student by Name")
print("5. Generate Report (Avg Marks > 70%)")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
usn = input("Enter USN: ")
name = input("Enter Name: ")
gender = input("Enter Gender: ")
marks1 = float(input("Enter Marks1: "))
marks2 = float(input("Enter Marks2: "))
marks3 = float(input("Enter Marks3: "))
add_student(usn, name, gender, marks1, marks2, marks3)
print(f"Student {name} added successfully.")
if __name__ == "__main__":
main()
Write a program to enter names of employees and their salaries as input and
store them in a dictionary.
count = 1
employee = dict() #create an empty dictionary
while count <= num:
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k,'\t\t',employee[k])
Output:
Enter the number of employees to be stored: 5
Enter the name of the Employee: 'Tarun'
Enter the salary: 12000
Enter the name of the Employee: 'Amina'
Enter the salary: 34000
Enter the name of the Employee: 'Joseph'
Enter the salary: 24000
Enter the name of the Employee: 'Rahul'
Enter the salary: 30000
Enter the name of the Employee: 'Zoya'
Enter the salary: 25000
EMPLOYEE_NAME SALARY
'Tarun' 12000
'Amina' 34000
'Joseph' 24000
'Rahul' 30000
'Zoya' 25000
****End****
Module 2
Manipulating Strings
def charCount(ch,st):
count = 0
for character in st:
if character == ch: count += 1
return count #end of function
Output:
def replaceVowel(st):
newstr=''
for character in st:
if character in 'aeiouAEIOU':
newstr += '*'
else:
newstr += character
return newstr
st = input("Enter a String: ")
st1 = replaceVowel(st)
Output:
Enter a String: Hello World
The original String is: Hello World
The modified String is: H*ll* W*rld
Output:
Enter a string: Hello World
dlroW olleH
def reverseString(st):
newstr = '' #create a new string
length = len(st)
for i in range(-1,-length-1,-1):
newstr += st[i]
return newstr #end of function
st = input("Enter a String: ")
st1 = reverseString(st)
print("The original String is:",st)
print("The reversed String is:",st1)
Output:
Enter a String: Hello World
The original String is: Hello World
def checkPalin(st):
i=0
j = len(st) - 1
while(i <= j):
if(st[i] != st[j]):
return False
i += 1
j -= 1
return True #end of function
st = input("Enter a String: ")
result = checkPalin(st)
if result == True:
print("The given string",st,"is a palindrome")
else:
print("The given string",st,"is not a palindrome")
Output 1:
Enter a String: madam
The given string madam is a palindrome
Output 2:
Enter a String: Computer
The given string Computer is not a palindrome