>
This section is included to assist the students to perform the activities present in the book. It includes detailed steps that are to be performed by the students to complete and achieve the objectives of the book.
Solution:
>>> print("Happy birthday")
Happy birthday
>>> 17 + 35 * 2
87
>>> print(1, 2, 3, 4, 5, 6, 7, 8, 9)
1 2 3 4 5 6 7 8 9
>>>
Solution:
import sys
print("*---------------------------------")
print("|", "First name: ", sys.argv[1])
print("|", "Second name: ", sys.argv[2])
print("*---------------------------------")
Solution:
distance_in_km = 150
time_in_hours = 2
distance_in_mi = distance_in_km / 1.6
distance_in_mtrs = distance_in_km * 1000
We'll then calculate the time in seconds based on the time in hours:
time_in_seconds = time_in_hours * 3600
speed_in_kph = distance_in_km / time_in_hours
speed_in_mph = distance_in_mi / time_in_hours
speed_in_mps = distance_in_mtrs / time_in_seconds
print("The speed in kilometers per hour is:", speed_in_kph)
print("The speed in miles per hour is:", speed_in_mph)
print("The speed in meters per second is:", speed_in_mps)
Solution:
PI = 3.14159
radius = 7
area = PI * radius**2
circumference = 2 * PI * radius
The ** operator raises the value to the specified exponent; in this case, the exponent is 2.
print("Circumference of the circle:", circumference)
print("Area of the circle:", area)
Solution:
>>> if 5 > 2:
... print("Greater than")
... x = 5
... print(x * 2)
... else:
... print("Less than")
... print(2)
Solution:
"""
This script generates a multiplication table from 1 to 10 for
any given number.
"""
number = int(input("Generate a multiplication table for: "))
print("_" * 20)
print("1:", number)
print("2:", number * 2)
print("3:", number * 3)
print("4:", number * 4)
print("5:", number * 5)
print("6:", number * 6)
print("7:", number * 7)
print("8:", number * 8)
print("9:", number * 9)
print("10:", number * 10)
print("_" * 20)
Solution:
>>> 5 * (4 - 2) + 100 / ( 5/2 ) * 2
90.0
Solution:
days = int(input("Number of days:"))
years = days // 365
weeks = (days % 365) // 7
days = days - ((years * 365) + (weeks * 7))
print("Years:", years)
print("Weeks:", weeks)
print("Days:", days)
Solution:
Solution:
string = input("String to convert: ")
n = int(input("How many last letters should be converted? "))
# First part of the string
start = string[:len(string) - n]
# last part of the string that we're converting.
end = string[len(string) - n:]
print(start + end.upper())
Solution:
sentence = input("Sentence: ")
query = input("Word to look for in sentence: ")
# sanitize our inputs
sentence = sentence.lower().strip()
query = query.lower().strip()
num_occurrences = sentence.count(query)
Then, we will print the results:
print(f"There are {num_occurrences} occurrences of '{query}' in the sentence.")
Solution:
array = [55, 12, 37, 831, 57, 16, 93, 44, 22]
print("Array: ", array)
n = int(input("Number of elements to fetch from array: "))
print(array[0: n])
Solutions:
n = 124
if n % 2 == 0:
print("Even")
age = 25
if age >= 18:
print("Here is your legal pass.")
letter = "b"
if letter not in ["a", "e", "i", "o", "u"]:
print(f"'{letter}' is not a vowel.")
Solution:
answer = input("Return TRUE or FALSE: Python was released in 1991: ")
if answer == "TRUE":
print('Correct')
elif answer == "FALSE":
print('Wrong')
elif answer != ("TRUE" or "FALSE"):
print('Please answer TRUE or FALSE')
print('Bye!')
Solution:
user_pass = "random"
valid = False
while not valid:
password = input("please enter your password: ")
if password == user_pass:
print("Welcome back user!")
valid = True
else:
print("invalid password, try again... ")
Your block of code should look as follows; take note of the indentation:
user_pass = "random"
valid = False
while not valid:
password = input("please enter your password: ")
if password == user_pass:
print("Welcome back user!")
valid = True
else:
print("invalid password, try again... ")
Solution:
>>> total = 0
>>> for number in range(2,101,2):
total += number
>>> print(total)
Solution:
for even in range(2,11,2):
for odd in range(1,11,2):
val = even + odd
print(even, "+", odd, "=", val)
Solution:
for number in range(0,200):
if number == 0:
continue
elif number % 3 != 0:
continue
elif type(number) != int:
continue
else:
pass
print(number)
Solution:
def print_arguments(*args):
for value in args:
if type(value) == int:
continue
print(value)
Solution:
>>> answer = lambda number, power : number ** power
Solution:
>>> wild = ["Lion", "Zebra", "Panther", "Antelope"]
>>> wild
['Lion', 'Zebra', 'Panther', 'Antelope']
>>> wild.append("Elephant")
>>> wild
['Lion', 'Zebra', 'Panther', 'Antelope', 'Elephant']
>>> animals = []
>>> animals.extend(wild)
>>> animals
['Lion', 'Zebra', 'Panther', 'Antelope', 'Elephant']
>>> animals.insert(2, "Cheetah")
>>> animals
['Lion', 'Zebra', 'Cheetah', 'Panther', 'Antelope', 'Elephant']
>>> animals.pop(1)
'Zebra'
>>> animals.insert(1, "Giraffe")
>>> animals
['Lion', 'Giraffe', 'Cheetah', 'Panther', 'Antelope', 'Elephant']
>>> animals.sort(key=None, reverse=False)
>>> animals
['Antelope', 'Cheetah', 'Elephant', 'Giraffe', 'Lion', 'Panther']
Solution:
pets = ('cat', 'cat', 'cat', 'dog', 'horse')
c = pets.count("cat")
d = len(pets)
if (c/d)*100 > 50.0:
print("There are too many cats here")
else:
print("Everything is good")
Solution:
>>> d = dict()
>>> type(d)
<class 'dict'>
Solution:
def sentence_analyzer(sentence):
solution = {}
for char in sentence:
if char is not ' ':
if char in solution:
solution[char] += 1
else:
solution[char] = 1
return solution
Solution:
def dictionary_masher(dict_a, dict_b):
for key, value in dict_b.items():
if key not in dict_a:
dict_a[key] = value
return dict_a
Solution:
The set function can help us create our function:
def set_maker(the_list):
return set(the_list)
Solution:
def find_union(list_a, list_b):
union = []
for element in list_a + list_b:
if element not in union:
union.append(element)
return union
Solution:
This is the MobilePhone class definition:
class MobilePhone:
def __init__(self, display_size, ram, os):
self.display_size = display_size
self.ram = ram
self.os = os
The solution can also be found in the code files for this chapter in the file named mobile_phone1.py.
Solution:
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def circumference(self):
return 2 * math.pi * self.radius
def change_radius(self, new_radius):
self.radius = new_radius
circle = Circle(7)
while True:
radius = float(input("Circle radius: "))
circle.change_radius(radius)
print("Area:", circle.area())
print("Circumference:", circle.circumference())
The solution can also be found in the code files for this chapter in the file named
circle.py.
Solution:
class Elevator:
occupancy_limit = 8
def __init__(self, occupants):
if occupants > self.occupancy_limit:
print("The maximum occupancy limit has been exceeded."
f" {occupants - self.occupancy_limit} occupants must exit the elevator.")
self.occupants = occupants
elevator1 = Elevator(6)
print("Elevator 1 occupants:", elevator1.occupants)
elevator2 = Elevator(10)
print("Elevator 2 occupants:", elevator2.occupants)
The solution can also be found in the code files for this book in the file named elevator.py.
Solution:
class MusicPlayer:
firmware_version = 1.0
def __init__(self):
self.__tracks = ["Moonage Daydream", "Starman", "Life on Mars?"]
self.current_track = None
def play(self):
self.current_track = self.__tracks[0]
def list_tracks(self):
return self.__tracks
@classmethod
def update_firmware(cls, new_version):
if new_version > cls.firmware_version:
cls.firmware_version = new_version
player = MusicPlayer()
print("Tracks currently on device:", player.list_tracks())
MusicPlayer.update_firmware(2.0)
print("Updated player firmware version to", player.firmware_version)
player.play()
print("Currently playing", f"'{player.current_track}'")
The solution can also be found in the code files for this course in the file named musicplayer.py.
Solution:
class Cat:
def __init__(self, mass, lifespan, speed):
self.mass_in_kg = mass
self.lifespan_in_years = lifespan
self.speed_in_kph = speed
def vocalize(self):
print("Chuff")
def __str__(self):
return f"The {type(self).__name__.lower()} "
f"weighs {self.mass_in_kg}kg,"
f" has a lifespan of {self.lifespan_in_years} years and "
f"can run at a maximum speed of {self.speed_in_kph}kph."
class Tiger(Cat):
def __init__(self, mass, lifespan, speed):
super().__init__(mass, lifespan, speed)
self.coat_pattern = "striped"
def __str__(self):
facts = super().__str__()
facts = f"{facts} It also has a {self.coat_pattern} coat."
return facts
tiger = Tiger(310, 26, 65)
print(tiger)
The solution for this activity can also be found in the tiger.py file in the attached code files for this chapter.
Solution:
class MobilePhone:
def __init__(self, memory):
self.memory = memory
class Camera:
def take_picture(self):
print("Say cheese!")
class CameraPhone(MobilePhone, Camera):
pass
cameraphone = CameraPhone("200KB")
cameraphone.take_picture()
print(cameraphone.memory)
The solution for this activity can also be found in the cameraphone.py file in the attached code files for this chapter.
Solution:
>>> import itertools
>>> dir(itertools)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', '_grouper', '_tee', '_tee_dataobject', 'accumulate', 'chain', 'combinations', 'combinations_with_replacement', 'comp
ress', 'count', 'cycle', 'dropwhile', 'filterfalse', 'groupby', 'islice', 'permutations', 'product', 'repeat', 'starmap', 'takewhile', 'tee', 'zip_longest']
>>> help(itertools)
You should see an output such as this:
Help on built-in module itertools:
NAME
itertools - Functional tools for creating and using iterators.
DESCRIPTION
Infinite iterators:
count(start=0, step=1) --> start, start+step, start+2*step, ...
cycle(p) --> p0, p1, ... plast, p0, p1, ...
repeat(elem [,n]) --> elem, elem, elem, ... endlessly or up to n times
Iterators terminating on the shortest input sequence:
accumulate(p[, func]) --> p0, p0+p1, p0+p1+p2
chain(p, q, ...) --> p0, p1, ... plast, q0, q1, ...
chain.from_iterable([p, q, ...]) --> p0, p1, ... plast, q0, q1, ...
compress(data, selectors) --> (d[0] if s[0]), (d[1] if s[1]), ...
dropwhile(pred, seq) --> seq[n], seq[n+1], starting when pred fails
groupby(iterable[, keyfunc]) --> sub-iterators grouped by value of keyfunc(v)
filterfalse(pred, seq) --> elements of seq where pred(elem) is False
islice(seq, [start,] stop [, step]) --> elements from
seq[start:stop:step]
starmap(fun, seq) --> fun(*seq[0]), fun(*seq[1]), ...
tee(it, n=2) --> (it1, it2 , ... itn) splits one iterator into n
takewhile(pred, seq) --> seq[0], seq[1], until pred fails
zip_longest(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ...
Combinatoric generators:
product(p, q, ... [repeat=1]) --> cartesian product
permutations(p[, r])
combinations(p, r)
combinations_with_replacement(p, r)
CLASSES
builtins.object
accumulate
chain
combinations
combinations_with_replacement
compress
count
cycle
dropwhile
filterfalse
groupby
islice
/var/folders/lb/k8ws21qn1x5gxq9zbrlqxp9w0000gn/T/tmp__ayalkd
Solution:
def package_enumerator(package):
"""
List the resources defined in a package or module.
"""
resources = dir(package)
for resource in resources:
print(resource)
import string
package_enumerator(string)
Solution:
import random
def random_number_generator(l):
"""
Generate a list of random numbers of length l.
"""
output = []
for i in range(l):
output.append(random.randint(0, 1000))
return output
Solution:
with open("myfile.txt", 'w') as f:
f.write("I love Python")
Solution:
import csv
output_data = []
with open('input.csv', 'r') as f:
mock_data_reader = csv.reader(f)
output_data = []
line_count = 1
for row in mock_data_reader:
if line_count != 1:
row[1] = int(row[1]) * 15
output_data.append(row)
line_count += 1
with open('output.csv', 'w') as f:
fields = ['name', 'wages']
output_writer = csv.DictWriter(f, fieldnames=fields)
output_writer.writeheader()
for line in output_data:
output_writer.writerow(
{
'name': line[0],
'wages': line[1]
}
)
This sample solution is also present in the wage_calculator.py file in the accompanying code files.
Solution:
KeyError:
building = dict(
name="XYZ Towers",
type="Business Premises"
)
print(f"I went to visit {building['name']} yesterday at {building['street']}.")
AttributeError:
import string
letters = string.asciiletters
Solution:
import random
try:
print(random.randinteger(1,10))
except AttributeError:
print("Oops! Something went wrong")
Solution:
class RecipeNotValidError(Exception):
def __init__(self):
self.message = "Your recipe is not valid"
try:
raise RecipeNotValidError
except RecipeNotValidError as e:
print(e.message)
18.220.111.87