0% found this document useful (0 votes)
90 views

Introduction To Programming - Exercise Sheet 8 - Solution Introduction To Programming, ITU (Autumn 2022)

The document provides solutions to exercises on Python programming. It includes solutions for tasks involving adding documentation to functions, creating classes for restaurants and ice cream stands, inheriting from classes, importing classes from different modules, and creating a Die class to roll random numbers. The solutions demonstrate best practices for writing Python code, including adding documentation, defining methods and attributes, inheritance, importing and using classes across modules, and utilizing random number generation.

Uploaded by

Jonas Danielsen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views

Introduction To Programming - Exercise Sheet 8 - Solution Introduction To Programming, ITU (Autumn 2022)

The document provides solutions to exercises on Python programming. It includes solutions for tasks involving adding documentation to functions, creating classes for restaurants and ice cream stands, inheriting from classes, importing classes from different modules, and creating a Die class to roll random numbers. The solutions demonstrate best practices for writing Python code, including adding documentation, defining methods and attributes, inheritance, importing and using classes across modules, and utilizing random number generation.

Uploaded by

Jonas Danielsen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Introduction to programming - Exercise Sheet 8 - Solution · Introduction to Programming, ITU (Autumn 2022) 08/11/2022, 18.

01

Introduction to programming - Exercise Sheet 8


- Solution
Task 1 (Adding Program Documentation)
Consider the following function:

def a (x):
l = []
for b in x:
if b < 0:
l.append(b)
return l

Improve this function by making variable and function names more descriptive. Additionally,
add a docstring that describes what this function is doing.

Solution:

"""
A function taking a list of integers or floats and
returns a list containing the numbers that are less than zero
"""

def lessThanZero
lessThanZero(num):
result = []
for n in num:
if n < 0:
result.append(n)
return result

print
print(lessThanZero([-
-2, - 1, 0, 1, 2, 10]))

Task 2 (Exercise 9.1 & 9.2, Python Crash Course)


Make a class called Restaurant . The __init__() method for Restaurant should store
two attributes: a restaurant_name and a cuisine_type . Make a method called
describe_restaurant() that prints these two pieces of information, and a method
called open_restaurant() that prints a message indicating that the restaurant is open.

https://github.itu.dk/pages/ip/2022/exercises/exercise_08_solutions/ Page 1 of 7
Introduction to programming - Exercise Sheet 8 - Solution · Introduction to Programming, ITU (Autumn 2022) 08/11/2022, 18.01

1. Make an instance called restaurant from your class. Print the two attributes
individually, and then call both methods.
2. Make two more instances and call describe_restaurant() on them.

Solution:

class Restaurant
Restaurant():
"""A class representing a restaurant."""
def __init__
__init__(self, restaurant_name, cuisine_type):
"""Initialize the restaurant."""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type

def describe_restaurant
describe_restaurant(self):
"""Display a summary of the restaurant."""
msg = self.restaurant_name + " serves wonderful " + self.cuisine_ty
print
print("\n" + msg)

def open_restaurant
open_restaurant(self):
"""Display a message that the restaurant is open."""
print
print(self.restaurant_name + ' is open. Come on in!')

# 1
restaurant = Restaurant("Tommy's Burger Joint", "burgers")
print
print(restaurant.restaurant_name + "\n" + restaurant.cuisine_type)
restaurant.describe_restaurant()
restaurant.open_restaurant()

# 2
rest_alch = Restaurant("Alchemist", "holistic cuisine")
rest_alch.describe_restaurant()

rest_baka = Restaurant("Baka d'Busk", "vegetarian cuisine")


rest_baka.describe_restaurant()

Task 3 (Exercise 9.4, Python Crash Course)


Start with your solution from Task 2. Add an attribute called number_served with a default
value of 0 . Create an instance called restaurant from this class. Print the number of
customers the restaurant has served, and then change this value and print it again. Add a
method called set_number_served() that lets you set the number of customers that

https://github.itu.dk/pages/ip/2022/exercises/exercise_08_solutions/ Page 2 of 7
Introduction to programming - Exercise Sheet 8 - Solution · Introduction to Programming, ITU (Autumn 2022) 08/11/2022, 18.01

have been served. Call this method with a new number and print the value again . Add a
method called increment_number_served() that lets you increment the number of
customers who’ve been served. Call this method with any number you like that could
represent how many customers were served in, say, a day of business.

Make sure to add documentation to your methods. Solution:

https://github.itu.dk/pages/ip/2022/exercises/exercise_08_solutions/ Page 3 of 7
Introduction to programming - Exercise Sheet 8 - Solution · Introduction to Programming, ITU (Autumn 2022) 08/11/2022, 18.01

class Restaurant
Restaurant():
"""A class representing a restaurant."""
def __init__
__init__(self, restaurant_name, cuisine_type):
"""Initialize the restaurant."""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0

# CODE FROM TASK 2 OMITTED HERE

def set_number_served
set_number_served(self, number_served):
"""Allow user to set the number of customers that have been served."
self.number_served = number_served

def increment_number_served
increment_number_served(self, additional_served):
"""Allow user to increment the number of customers served."""
self.number_served += additional_served

restaurant = Restaurant("Tommy's Burger Joint", "burgers")


restaurant.describe_restaurant()

# 1
print
print("\nNumber served: " + str(restaurant.number_served))
restaurant.number_served = 430
print
print("Number served: " + str(restaurant.number_served))

# 2
restaurant.set_number_served(1257)
print
print("Number served: " + str(restaurant.number_served))

# 3
restaurant.increment_number_served(239)
print
print("Number served: " + str(restaurant.number_served))

Task 4 (Exercise 9.6, Python Crash Course)


An ice cream stand is a specific kind of restaurant. Write a class called IceCreamStand
that inherits from the Restaurant class you wrote above.

Add an attribute called flavors that stores a list of ice cream flavors . Write a method that

https://github.itu.dk/pages/ip/2022/exercises/exercise_08_solutions/ Page 4 of 7
Introduction to programming - Exercise Sheet 8 - Solution · Introduction to Programming, ITU (Autumn 2022) 08/11/2022, 18.01

displays these flavors . Create an instance of IceCreamStand , and call this method.

Solution:

# CODE FROM TASK 3 OMITTED HERE

class IceCreamStand
IceCreamStand(Restaurant):
"""Represent an ice cream stand."""

def __init__
__init__(self, restaurant_name, cuisine_type=='ice cream'):
"""Initialize an ice cream stand with default cuisine type."""
super().__init__(restaurant_name, cuisine_type)
self.flavors = []

def show_flavors
show_flavors(self):
"""Display the flavors available."""
print
print("\nWe have the following flavors available:")
for flavor in self.flavors:
print
print("- " + flavor.title())

shop = IceCreamStand('Tri-colour')
shop.flavors = ['Vanilla', 'Chocolate', 'Strawberry']

shop.describe_restaurant()
shop.show_flavors()

Task 5 (Adapted Exercise 9.10, Python Crash Course)


Store your latest Restaurant class in one module and your IceCreamStand class in
another one. Let the module with the IceCreamStand import the Restaurant class. In a
third module create a Restaurant and IceCreamStand instance respectively, and call
respectively one of their methods to show that the import statement is working properly.

Solution:

https://github.itu.dk/pages/ip/2022/exercises/exercise_08_solutions/ Page 5 of 7
Introduction to programming - Exercise Sheet 8 - Solution · Introduction to Programming, ITU (Autumn 2022) 08/11/2022, 18.01

from icecreamstand import IceCreamStand

shop = IceCreamStand('Ismageriet')
shop.flavors = ['Havtorn', 'Toffee', 'Coconut']
shop.describe_restaurant()
shop.open_restaurant()
shop.show_flavors()

Task 6 (Exercise 9.14, Python Crash Course)


Make a class Die with one attribute called sides , which has a default value of 6. Write a
method called roll_die() that prints a random number between 1 and the number of
sides the die has. Make a 6-sided die and roll it 10 times. Make a 10-sided die and a 20-
sided die. Roll each die 10 times.

Solution:

from random import randint

class Die
Die():
"""Represent a die, which can be rolled."""

def __init__
__init__(self, sides = 6):
"""Initialize the die."""
self.sides = sides

def roll_die
roll_die(self):
"""Return a number between 1 and the number of sides."""
return randint(1, self.sides)

# Make a 6-sided die, and show the results of 10 rolls.


d6 = Die()

results = []
for roll_num in range(10):
result = d6.roll_die()
results.append(result)
print
print("10 rolls of a 6-sided die:")
print
print(results)

# Make a 10-sided die, and show the results of 10 rolls.

https://github.itu.dk/pages/ip/2022/exercises/exercise_08_solutions/ Page 6 of 7
Introduction to programming - Exercise Sheet 8 - Solution · Introduction to Programming, ITU (Autumn 2022) 08/11/2022, 18.01

d10 = Die(sides=
=10)

results = []
for roll_num in range(10):
result = d10.roll_die()
results.append(result)
print
print("\n10 rolls of a 10-sided die:")
print
print(results)

# Make a 20-sided die, and show the results of 10 rolls.


d20 = Die(sides=
=20)

results = []
for roll_num in range(10):
result = d20.roll_die()
results.append(result)
print
print("\n10 rolls of a 20-sided die:")
print
print(results)

https://github.itu.dk/pages/ip/2022/exercises/exercise_08_solutions/ Page 7 of 7

You might also like