Python File
Python File
PRACTICAL FILE
Submitted in partial fulfillment for the award of
BACHELOR OF TECHNOLOGY
(CSE), 2nd year
Submitted by
RUPESH VARSHNEY
Roll No:- 2001090100045
Submitted To
Dr. Lalit Mohan Gupta
(Python Language
Programming Lab: KCS-453)
[Session: 2021-2022]
INDEX
Sr.No. Name of Experiment Sign.
Write a program in Python for List Problem.
1
Write a program in Python to use sort() & Len().
2
Write a program in Python for LOOPS Problem.
3
Write a program in Python to use Slices in List .
4
Write a program in Python for Conditional Statements.
5
Write a program in Python to use Dictionary.
6
Write a program in Python to use Dictionary with List.
7
Write a program in Python to use Functions.
8
Write a program in Python to use Functions with List &
9 Dictionary.
Write a program in Python to import file & use try: & Except:
10 Keywords.
Programming Lab
Semester:- IV
Names: Store the names of a few of your friends in a list called names Print each
person's name by accessing each element in the list, one at a time
Greetings: Start with the list you used in Exercise 3-1, but instead of just
printing each person's name, printing a message to them. The text of each message
should be the same, but each message should be personalised with the person's
name.
Your Own List: Think of your favourite mode of transportation, such as a motorcycle
or a car, and make a list that stores several examples. Use your list to print a series of
statements about these items, such as "I would like to own a Honda motorcycle."
Soln:
print(names[0])
print(names[1])
print(names[2])
1
favorite_transportation = ['car', "Motorcycle"]
print("I go to work using {}".format(favorite_transportation[0]))
print("I would like to buy a Honda {}".format(favorite_transportation[1]))
2. More Guests: You just found a bigger dinner table, so now more space is
available. Think of three more guests to invite to dinner.Start with your
program from Exercise 3-4 or Exercise 3-5. Add a print call to the end of your
program informing people that you found a bigger dinner table.
Use insert() to add one new guest to the beginning of your list.
Use insert() to add one new guest to the middle of your list.
Use append() to add one new guest to the end of your list.
Soln:-.
3. If you could invite anyone, living or deceased, to dinner, who would you invite?
Make a list that includes at least three people you’d like to invite to dinner.
Then use your list to print a message to each person, inviting them to dinner.
You just heard that one of your guests can’t make the dinner, so you need to send out
a new set of invitations. You’ll have to think of someone else to invite.
2
Start with your program from Exercise 3-4. Add a print statement at the end of your
program stating the name of the guest who can’t make it.
Modify your list, replacing the name of the guest who can’t make it with the name of
the new person you are inviting.
Print a second set of invitation messages, one for each person who is still in your list.
Soln:-
name = guests[0].title()
print(name + ", please come to dinner.")
name = guests[1].title()
print(name + ", please come to dinner.")
name = guests[2].title()
print(name + ", please come to dinner.")
name = guests[1].title()
name = guests[1].title()
print(name + ", please come to dinner.")
name = guests[2].title()
print(name + ", please come to dinner.")
3
4. Shrinking Guest List: You just found out that your new dinner table won't arrive
in time for the dinner, and you have space for only two guests.
Start with your program from Exercise 3-6. Add a new line that prints a message
saying that you can invite only two people for dinner
Use pop() to remove guests from your list one at a time until only two names remain
in your list. Each time you pop a name from your list, print a message to that person
letting them know you're sorry you can't invite them to dinner
Print a message to each of the two people still on your list, letting them know they're
still invited
Use del to remove the last two names from your list, so you have an empty list Print
your list to make sure you actually have an empty list at the end of your program.
Soln:-
name = guests.pop()
print("Sorry, " + name.title() + " there's no room at the table.")
name = guests.pop()
print("Sorry, " + name.title() + " there's no room at the table.")
name = guests.pop()
print("Sorry, " + name.title() + " there's no room at the table.")
name = guests.pop()
print("Sorry, " + name.title() + " there's no room at the table.")
name = guests[1].title()
print(name + ", please come to dinner.")
4
print(guests)
5. Seeing the World: Think of at least five places in the world you'd like to visit.
Store the locations in a list. Make sure the list is not in alphabetical order.
Print your list in its original order. Don't worry about printing the list neatly, just
It is a raw Python list. Use sorted() to print your list in alphabetical order without
modifying the actual list.
Show that your list is still in its original order by printing it.
Use sorted() to print your list in reverse alphabetical order without changing the order
of the original list.
Soln-:.
locations = ['Shimla', 'Iskcon Temple', 'Taj mahal', 'Golden Temple', 'Sri lanka']
print("Original order:")
print(locations)
print("\nAlphabetical:")
print(sorted(locations))
print("\nOriginal order:")
print(locations)
print("\nReverse alphabetical:")
print(sorted(locations, reverse=True))
5
6. Dinner Guests: Working with one of the programs from Exercises 3-4
through 3-7 (page 42), use len() to print a message indicating the number
of people you are inviting to dinner.
Soln:-
7. Think of at least three kinds of your favourite pizza. Store these pizza names in
a list, and then use a for loop to print the name of each pizza.
Modify your for loop to print a sentence using the name of the pizza instead of
printing just the name of the pizza. For each pizza you should have one line of output
containing a simple statement like I like pepperoni pizza.
Add a line at the end of your program, outside the for loop, that states how much you
like pizza. The output should consist of three or more lines about the kinds of pizza
you like and then an additional sentence, such as I really love pizza!
Soln:-.
6
for pizza in favorite_pizzas:
print(pizza)
print("\n")
Soln:-
7
9. Counting to Twenty: Use a for loop to print the numbers from 1 to 20, inclusive
One Million: Make a list of the numbers from one to one million, and then use a for
loop to print the numbers. (If the output is taking too long, stop it by pressing ctrl-C or
by closing the output window.
Summing a Millions Make a list of the numbers from one to one million, and then use
min() and max() to make sure your list actually starts at one and ends at one million.
Also, use the sum() function to see how quickly Python can add a million numbers
Odd Numbers: Use the third argument of the range() function to make a list of the odd
numbers from 1 to 20. Use a for loop to print each number
Threes: Make a list of the multiples of 3 from 3 to 30. Use a for loop to print the
numbers in your list
Soln:-
8
numbers = list(range(1, 1000001))
print(min(numbers))
print(max(numbers))
print(sum(numbers))
9
10. A number raised to the third power is called a cube. For example, the cube of 2
is written as 2**3 in Python. Make a list of the first 10 cubes (that is, the cube of
each integer from 1 through 10), and use a for loop to print out the value of
each cube.
Use a list comprehension to generate a list of the first 10 cubes.
Soln:-
cubes = []
for number in range(1, 11):
cube = number**3
cubes.append(cube)
11. Make a copy of the list of pizzas, and call it friend_pizzas. Then, do the
following:
10
Soln-:
favorite_pizzas.append("mayonnaise")
friend_pizzas.append('extra cheese')
12. Slices: Using one of the programs you wrote in this chapter, add several
lines to the end of the program that do the following:
• Print the message The first three items in the list are: use a slice to
print.
• Print the message Three items from the middle of the list are:. Use a slice to print
.
• Print the message The last three items in the list are: Use a slice to print.
Soln-:
11
13. Imagine an alien was just shot down in a game. Create a variable called
alien_color and assign it a value of 'green', 'yellow', or 'red'.
Write an if statement to test whether the alien’s colour is green. If it is, print a
message that the player just earned 5 points.
Write one version of this program that passes the if test and another tha fails. (The
version that fails will have no output.)
Soln-:
alien_color = 'green'
if alien_color == 'green':
print("You just earned 5 points!")
alien_color = 'red'
if alien_color == 'green':
print("You just earned 5 points!")
No output
14. Choose a colour for an alien as you did in Exercise 5-3, and write an if-else
chain.
If the alien’s colour is green, print a statement that the player just earned 5 points for
shooting the alien.
If the alien’s colour isn’t green, print a statement that the player just earned 10 points.
Write one version of this program that runs the if block and another that runs the else
block.
Soln-:
alien_color = 'green'
if alien_color == 'green':
print("You just earned 5 points!")
else:
print("You just earned 10 points!")
12
alien_color = 'red'
if alien_color == 'green':
print("You just earned 5 points!")
else:
print("You just earned 10 points!")
15. Turn your if-else chain from Exercise 5-4 into an if-elif-else chain.
If the alien is green, print a message that the player earned 5 points.
If the alien is yellow, print a message that the player earned 10 points.
If the alien is red, print a message that the player earned 15 points.
Write three versions of this program, making sure each message is printed for the
appropriate colour alien.
alien_color = 'red'
Soln-:
alien_color = 'red'
if alien_color == 'green':
print("You just earned 5 points!")
elif alien_color == 'yellow':
print("You just earned 10 points!")
else:
print("You just earned 15 points!")
alien_color = 'green'
if alien_color == 'green':
print("You just earned 5 points!")
elif alien_color == 'yellow':
print("You just earned 10 points!")
else:
print("You just earned 15 points!")
13
alien_color = 'yellow'
if alien_color == 'green':
print("You just earned 5 points!")
elif alien_color == 'yellow':
print("You just earned 10 points!")
else:
print("You just earned 15 points!")
16. Make a list of five or more usernames, including the name 'admin'. Imagine you
are writing code that will print a greeting to each user after they log in to a
website. Loop through the list, and print a greeting to each user.
If the username is 'admin', print a special greeting, such as Hello admin, would you
like to see a status report?
Otherwise, print a generic greeting, such as Hello Eric, thank you for logging in again.
Soln-:.
14
Make a list of five or more usernames called current_users. Make another list of five
usernames called new_users. Make sure one or two of the new usernames are also in
the current_users list.
Loop through the new_users list to see if each new username has already been used.
If it has, print a message that the person will need to enter a new username. If a
username has not been used, print a message saying that the username is available.
Make sure your comparison is case insensitive. If 'John' has been used, 'JOHN'
should not be accepted.
Soln-:
18. Write an if-elif-else chain that determines a person’s stage of life. Set a value for the
variable age, and then:
If the person is less than 2 years old, print a message that the person is a baby.
If the person is at least 2 years old but less than 4, print a message that the person is a
toddler.
If the person is at least 4 years old but less than 13, print a message that the person is a kid.
If the person is at least 13 years old but less than 20, print a message that the person is a
teenager
If the person is at least 20 years old but less than 65, print a message that the person is an
adult.
If the person is 65 or older, print a message that the person is an elder.
Soln:-.
age = 17
15
if age < 2:
print("You're a baby!")
elif age < 4:
print("You're a toddler!")
elif age < 13:
print("You're a kid!")
elif age < 20:
print("You're a teenager!")
elif age < 65:
print("You're an adult!")
else:
print("You're an elder!")
19. Make a list of your favourite fruits, and then write a series of independent if
statements that check for certain fruits in your list.
Make a list of your three favourite fruits and call it favorite_fruits.
Write five if statements. Each should check whether a certain kind of fruit is in your
list. If the fruit is in your list, the if block should print a statement, such as You really
like bananas!
Soln-:
favorite_fruits = ['blueberries', 'salmonberries', 'peaches']
if 'bananas' in favorite_fruits:
print("You really like bananas!")
if 'apples' in favorite_fruits:
print("You really like apples!")
if 'blueberries' in favorite_fruits:
print("You really like blueberries!")
if 'kiwis' in favorite_fruits:
print("You really like kiwis!")
if 'peaches' in favorite_fruits:
print("You really like peaches!")
16
20. Use a dictionary to store information about a person you know. Store their first
name, last name, age, and the city in which they live. You should have keys
such as first_name, last_name, age, and city. Print each piece of information
stored in your dictionary.
Soln-:.
person = {
'first_name': 'Ram',
'last_name': 'sharma',
'age': 43,
'city': 'Ayodhya',
}
print(person['first_name'])
print(person['last_name'])
print(person['age'])
print(person['city'])
21. Make a dictionary containing three major rivers and the country each river runs
through. One key-value pair might be 'nile': 'egypt'.
Use a loop to print a sentence about each river, such as The Nile runs through Egypt.
Use a loop to print the name of each river included in the dictionary.
Use a loop to print the name of each country included in the dictionary.
Soln-:
rivers = {
'nile': 'egypt',
'godavari': 'maharashtra',
'krishna': 'Telangana',
'Narmada': 'Mp',
'Tapti': 'Gujrat',
}
17
print("\nThe following rivers are included in this data set:")
for river in rivers.keys():
print("- " + river.title())
22. Now that you know how to loop through a dictionary, clean up the code by
replacing your series of print statements with a loop that runs through the
dictionary’s keys and values. When you’re sure that your loop works, add five
more Python terms to your glossary. When you run your program again, these
new words and meanings should automatically be included in the output.
Soln-:.
glossary = {
'string': 'A series of characters.',
'comment': 'A note in a program that the Python interpreter ignores.',
'list': 'A collection of items in a particular order.',
'loop': 'Work through a collection of items, one at a time.',
'dictionary': "A collection of key-value pairs.",
'key': 'The first item in a key-value pair in a dictionary.',
'value': 'An item associated with a key in a dictionary.',
'conditional test': 'A comparison between two values.',
'float': 'A numerical value with a decimal component.',
'boolean expression': 'An expression that evaluates to True or False.',
}
18
23. Make a list of people who should take the favourite languages poll. Include some
names that are already in the dictionary and some that are not.
Loop through the list of people who should take the poll. If they have already taken the poll,
print a message thanking them for responding. If they have not yet taken the poll, print a
message inviting them to take the poll.
Soln:-
favorite_languages = {
'jaya': 'python',
'salman': 'c',
'Aishwarya': 'ruby',
'papu': 'python',
}
print("\n")
19
24. Make two new dictionaries representing different people, and store all three
dictionaries in a list called people. Loop through your list of people. As you
loop through the list, print everything you know about each person
Soln-:.
people = []
person = {
'first_name': 'Ram',
'last_name': 'sharma',
'age': 43,
'city': 'Agra',
}
people.append(person)
person = {
'first_name': 'Kapil',
'last_name': 'Sharma',
'age': 45,
'city': 'punjab',
}
people.append(person)
person = {
'first_name': 'Rahul ',
'last_name': 'Gandhi',
'age': 52,
'city': 'Delhi',
}
people.append(person)
20
print(name + ", of " + city + ", is " + age + " years old.")
25. Make a dictionary called favorite_places. Think of three names to use as keys
in the dictionary, and store one to three favourite places for each person. To
make this exercise a bit more interesting, ask some friends to name a few of
their favourite places. Loop through the dictionary, and print each person’s
name and their favourite places.
Soln:-.
favorite_places = {
'Ram': ['Agra', 'Taj mahal', 'mount abu'],
'Shyam': ['hawaii', 'iceland'],
'Dilip': ['Abu dabi', 'red fort', 'south point']
}
26. Modify your program so each person can have more than one favorite number.
Then print each person’s name along with their favorite numbers.
Soln-:
favorite_numbers = {
'Ram': [42, 17],
'Shyam': [42, 39, 56],
'Labbu': [7, 12],
}
21
for name, numbers in favorite_numbers.items():
print("\n" + name.title() + " likes the following numbers:")
for number in numbers:
print(" " + str(number))
27. Make a dictionary called cities. Use the names of three cities as keys in your
dictionary. Create a dictionary of information about each city and include the country
that the city is in, its approximate population, and one fact about that city. The keys
for each city’s dictionary should be something like country, population, and fact. Print
the name of each city and all of the information you have stored about it.
Soln-:
cities = {
'santiago': {
'country': 'chile',
'population': 6158080,
'nearby mountains': 'andes',
},
'Kedarnath': {
'country': 'India',
'population': 876158080,
'nearby mountains': 'alaska range',
},
'kathmandu': {
'country': 'nepal',
'population': 1003285,
'nearby mountains': 'himilaya',
}
}
22
print("\n" + city.title() + " is in " + country + ".")
print(" It has a population of about " + str(population) + ".")
print(" The " + mountains + " mountains are nearby.")
28. Make a list called sandwich_orders and fill it with the names of various
sandwiches. Then make an empty list called finished_sandwiches. Loop
through the list of sandwich orders and print a message for each order, such
as I made your tuna sandwich. As each sandwich is made, move it to the list
of finished sandwiches. After all the sandwiches have been made, print a
message listing each sandwich that was made.
Soln-:
23
29. No Pastrami: Using the list sandwich_orders that make sure
The sandwich 'pastrami' appears in the list at least three times. Add code
near the beginning of your program to print a message saying the deli has
run out of pastrami, and then use a while loop to remove all occurrences of
'pastrami' from sandwich_orders. Make sure no pastrami sandwiches end up
in finished_sandwiches.
Soln-:
sandwich_orders = ['pastrami', "hamburger", "cheese burger", 'pastrami', "chicken
sandwich", 'pastrami', "big mac", "whopper burger"]
finished_sandwiches =[]
print("The Deli has run out of pastrami")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print()
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
print("I made a " + current_sandwich)
finished_sandwiches.append(current_sandwich)
print()
for finished_sandwich in finished_sandwiches:
print(finished_sandwich.title() + " is done")
24
30. Write a function called make_shirt() that accepts a size and the text of a
message that should be printed on the shirt. The function should print a
sentence summarizing the size of the shirt and the message printed on it.
Call the function once using positional arguments to make a shirt. Call the function a
second time using keyword arguments.
Modify the make_shirt() function so that shirts are large by default with a message
that reads I love Python. Make a large shirt and a medium shirt with the default
message, and a shirt of any size with a different message.
Write a function called describe_city() that accepts the name of a city and its country.
The function should print a simple sentence, such as Delhi in India. Give the
parameter for the country a default value. Call your function for three different cities,
at least one of which is not in the default country.
Soln-:
make_shirt()
make_shirt(size='medium')
make_shirt('small', 'Programmers are loopy.')
25
def describe_city(city, country='India'):
"""Describe a city."""
msg = city.title() + " is in " + country.title() + "."
print(msg)
describe_city('Vrindavan')
describe_city('Taj mahal', 'India')
describe_city('Red fort ','Delhi')
31. Write a function called city_country() that takes in the name of a city and its country.
The function should return a string formatted like this:
“Santiago, Chile”
Call your function with at least three city-country pairs, and print the value that’s returned.
Soln-:
26
32. Write a function called make_album() that builds a dictionary describing a
music album. The function should take in an artist name and an album title,
and it should return a dictionary containing these two pieces of information.
Use the function to make three dictionaries representing different albums. Print
each return value to show that the dictionaries are storing the album
information correctly.
Add an optional parameter to make_album() that allows you to store the number of
tracks on an album. If the calling line includes a value for the number of tracks, add
that value to the album’s dictionary. Make at least one new function call that includes
the number of tracks on an album.
Soln-:
def make_album(artist, title):
"""Build a dictionary containing information about an album."""
album_dict = {
'artist': artist.title(),
'title': title.title(),
}
return album_dict
33. Write a function that accepts a list of items a person wants on a sandwich. The
function should have one parameter that collects as many items as the
function call provides, and it should print a summary of the sandwich that is
being ordered. Call the function three times, using a different number of
arguments each time.
Soln:-
def make_sandwich(*items):
"""Make a sandwich with the given items."""
print("\nI'll make you a great sandwich:")
for item in items:
27
print(" ...adding " + item + " to your sandwich.")
print("Your sandwich is ready!")
34. Write a function that stores information about a car in a dictionary. the function
should always receive a manufacturer and a model name. It should then accept
an arbitrary number of keyword arguments. Call the function with the required
information and two other name-value pairs, such as a color or an optional
feature. Your function should work for a call like this one:
Print the dictionary that’s returned to make sure all the information was stored
correctly.
Soln-:
def make_car(manufacturer, model, **options):
"""Make a dictionary representing a car."""
car_dict = {
'manufacturer': manufacturer.title(),
'model': model.title(),
}
for option, value in options.items():
car_dict[option] = value
return car_dict
28
35. Put the functions for the example printing_models.py in a separate file called
printing_functions.py. Write an import statement at the top of printing_models.py, and
modify the file to use the imported functions.
Soln-:
def show_completed_models(completed_models):
"""Show all the models that were printed."""
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
printing_models.py:
import printing_functions as pf
pf.print_models(unprinted_designs, completed_models)
pf.show_completed_models(completed_models)
29
36. Messages- Make a list containing a series of short text messages. Pass the list
to a function called show_messages(), which prints each text message
Sending Messages- Start with a copy of your program from message. Write a function
called send_messages() that prints each text message and moves each message to a
new list called sent_messages as it’s printed. After calling the function, print both of
your lists to make sure the messages were moved correctly.
Archived Messages-Start with your work from Exercise. Call the function
send_messages() with a copy of the list of messages. After calling the function, print
both of your lists to show that the original list has retained its messages.
Soln:-
def show_messages(messages):
"""Print all messages in the list."""
for message in messages:
print(message)
def show_messages(messages):
"""Print all messages in the list."""
print("Showing all messages:")
for message in messages:
print(message)
30
print(current_message)
sent_messages.append(current_message)
sent_messages = []
send_messages(messages, sent_messages)
print("\nFinal lists:")
print(messages)
print(sent_messages)
def show_messages(messages):
"""Print all messages in the list."""
print("Showing all messages:")
for message in messages:
print(message)
sent_messages = []
send_messages(messages[:], sent_messages)
print("\nFinal lists:")
print(messages)
print(sent_messages)
31
37. Addition: One common problem when prompting for numerical input occurs
when people provide text instead of numbers. When you try to convert the
input to an int, you'll get a Value Error. Write a program that prompts for two
numbers Add them together and print the result Catch the Value Error if either
input value is not a number, and print a friendly error message Test your
program by entering two numbers and then by entering some text instead of a
number.
Soln:-
try:
x = input("Give me a number: ")
x = int(x)
except ValueError:
print("Sorry, I really needed a number.")
else:
sum = x + y
print("The sum of " + str(x) + " and " + str(y) + " is " + str(sum) + ".")
32
38. Search the Elements with the help of Linear Search .
Soln:-
list1 = [1 ,3, 5, 4, 7, 9]
key = 1
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
Soln:-
if array[mid] == x:
return mid
else:
high = mid - 1
return -1
array = [3, 4, 5, 6, 7, 8, 9]
x=4
if result != -1:
print("Element is present at index " + str(result))
else:
print("Not found")
Soln:-
def mergeSort(array):
if len(array) > 1:
i=j=k=0
# Driver program
if __name__ == '__main__':
array = [6, 5, 12, 10, 9, 1]
mergeSort(array)
Soln:-
Soln:-
n=3
TowerOfHanoi(n, 'A', 'C', 'B')
Soln:-
def prime_eratosthenes(n):
prime_list = []
for i in range(2, n+1):
if i not in prime_list:
print (i)
for j in range(i*i, n+1, i):
prime_list.append(j)
print(prime_eratosthenes(20));
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10