Appendix A

About

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.

Chapter 1: Introducing Python

Activity 1: Working with the Python Shell

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

>>>

Activity 2: Running Simple Python Scripts

Solution:

import sys

print("*---------------------------------")

print("|", "First name: ", sys.argv[1])

print("|", "Second name: ", sys.argv[2])

print("*---------------------------------")

Activity 3: Using Variables and Assign Statements

Solution:

  1. Open your editor.
  2. Create a file named calculate_speed.py and save it.
  3. On the first two lines, we'll declare our two variables for the distance in
    kilometers and the time in hours:

    distance_in_km = 150

    time_in_hours = 2

  4. In the next two lines, we'll calculate the distances in miles and the distance in meters based on the distance in kilometers:

    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

  5. Next, we'll calculate the speed in kilometers per hour, the speed in miles per hour, and the speed in miles per second:

    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

  6. Finally, we'll print out our results:

    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)

  7. We can now save our script and run it by using the python calculate_speed.py command.

Activity 4: Variable Assignment and Variable Naming Conventions

Solution:

  1. Open your editor.
  2. Create a file named circle.py and save it.
  3. On the first two lines, we'll declare our constant, π (PI), and the radius of the circle:

    PI = 3.14159

    radius = 7

  4. On the next two lines, we'll run our calculations:

    area = PI * radius**2

    circumference = 2 * PI * radius

    The ** operator raises the value to the specified exponent; in this case, the exponent is 2.

  5. Lastly, we'll display the results:

    print("Circumference of the circle:", circumference)

    print("Area of the circle:", area)

  6. We can now save our script and run it by using the python circle.py command.

Activity 5: Fixing Indentations in a Code Block

Solution:

>>> if 5 > 2:

... print("Greater than")

... x = 5

... print(x * 2)

... else:

... print("Less than")

... print(2)

Activity 6: Implementing User Input and Comments in a Script

Solution:

  1. Open your editor.
  2. Create a file named multiplication_table.py and save it.
  3. On the first line, we'll add a docstring explaining what our file does. Then, we'll assign number to the user's input and cast it to an integer:

    """

    This script generates a multiplication table from 1 to 10 for

    any given number.

    """

    number = int(input("Generate a multiplication table for: "))

  4. Next, we'll print 20 underscores as the top border of the table:

    print("_" * 20)

  5. We'll then multiply our number with each number from 1 to 10 and print that out:

    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)

  6. Finally, we'll print 20 underscores again for the bottom border of the table, as in step 4.

    print("_" * 20)

  7. Save the file and run it by using the python multiplication_table.py command.

Chapter 2: Data Types

Activity 7: Order of Operations

Solution:

>>> 5 * (4 - 2) + 100 / ( 5/2 ) * 2

90.0

Activity 8: Using Different Arithmetic Operators

Solution:

  1. Create a file named convert_days.py.
  2. On the first line, let's declare the user input. It's an integer, so we cast the string we get from the input function:

    days = int(input("Number of days:"))

  3. We can then calculate the number of years in that set of days. We floor divide to get an integer:

    years = days // 365

  4. Next, we convert the remaining days that weren't converted to years into weeks:

    weeks = (days % 365) // 7

  5. Then, we get any remaining days that weren't converted to weeks:

    days = days - ((years * 365) + (weeks * 7))

  6. Finally, we'll print everything out:

    print("Years:", years)

    print("Weeks:", weeks)

    print("Days:", days)

  7. We can then save and run the script by using the python convert_days.py command.

Activity 9: String Slicing

Solution:

  1. 'g'
  2. '9'
  3. 'fright'
  4. ' 1, 2, 3'
  5. 'A man, a plan, a canal: Panama'

Activity 10: Working with Strings

Solution:

  1. Create a file named convert_to_uppercase.py.
  2. On the first line, we'll request the user for the string to convert:

    string = input("String to convert: ")

  3. On the next line, we'll request the number of last letters to convert:

    n = int(input("How many last letters should be converted? "))

  4. Next, we'll get the first part of the string:

    # First part of the string

    start = string[:len(string) - n]

  5. Then, we'll get the last part of the string, that is, the one we'll be converting:

    # last part of the string that we're converting.

    end = string[len(string) - n:]

  6. Then, we will concatenate the first and last part back together with the last substring transformed:

    print(start + end.upper())

  7. Finally, we can run the script with the python convert_to_uppercase.py command.

Activity 11: Manipulating Strings

Solution:

  1. Create a file named count_occurrences.py.
  2. We'll take in the user inputs for the sentence and the query:

    sentence = input("Sentence: ")

    query = input("Word to look for in sentence: ")

  3. Next, we'll sanitize and format our inputs by removing the whitespace and converting them to lowercase:

    # sanitize our inputs

    sentence = sentence.lower().strip()

    query = query.lower().strip()

  4. We'll count the occurrences of the substring by using the str.count() method:

    num_occurrences = sentence.count(query)

    Then, we will print the results:

    print(f"There are {num_occurrences} occurrences of '{query}' in the sentence.")

  5. You can run the script by using the python count_occurrences.py command.

Activity 12: Working with Lists

Solution:

  1. Create a file named get_first_n_elements.py.
  2. On the first line, we'll create the array:

    array = [55, 12, 37, 831, 57, 16, 93, 44, 22]

  3. Next, we'll print the array out and fetch user input for the number of elements to fetch from the array:

    print("Array: ", array)

    n = int(input("Number of elements to fetch from array: "))

  4. Finally, we'll print out the slice of the array from the first element to the nth element:

    print(array[0: n])

  5. Then, we'll run the script by using the python get_first_n_elements.py command.

Activity 13: Using Boolean Operators

Solutions:

  1. The code block with the missing Boolean operator is added:

    n = 124

    if n % 2 == 0:

    print("Even")

  2. The code block with the missing Boolean operator is added:

    age = 25

    if age >= 18:

    print("Here is your legal pass.")

  3. The code block with the missing Boolean operator is added:

    letter = "b"

    if letter not in ["a", "e", "i", "o", "u"]:

    print(f"'{letter}' is not a vowel.")

Chapter 3: Control Statements

Activity 14: Working with the if Statement

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!')

Activity 15: Working with the while Statement

Solution:

  1. Define the password and the Boolean validator first:

    user_pass = "random"

    valid = False

  2. Initiate the while loop and ask for the user's input:

    while not valid:

    password = input("please enter your password: ")

  3. Validate the password and return an error if the input is invalid:

    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... ")

Activity 16: The for loop and range Function

Solution:

>>> total = 0

>>> for number in range(2,101,2):

total += number

>>> print(total)

Activity 17: Nested Loops

Solution:

for even in range(2,11,2):

for odd in range(1,11,2):

val = even + odd

print(even, "+", odd, "=", val)

Activity 18: Breaking out of Loops

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)

Chapter 4: Functions

Activity 19: Function Arguments

Solution:

def print_arguments(*args):

for value in args:

if type(value) == int:

continue

print(value)

Activity 20: Using Lambda Functions

Solution:

>>> answer = lambda number, power : number ** power

Chapter 5: Lists and Tuples

Activity 21: Using the List Methods

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']

Activity 22: Using Tuple Methods

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")

Chapter 6: Dictionaries and Sets

Activity 23: Creating a Dictionary

Solution:

>>> d = dict()

>>> type(d)

<class 'dict'>

Activity 24: Arranging and Presenting Data Using Dictionaries

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

Activity 25: Combining Dictionaries

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

Activity 26: Building a Set

Solution:

The set function can help us create our function:

def set_maker(the_list):

return set(the_list)

Activity 27: Creating Unions of Elements in a Collection

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

Chapter 7: Object-Oriented Programming

Activity 28: Defining a Class and Objects

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.

Activity 29: Defining Methods in a Class

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.

Activity 30: Creating Class Attributes

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.

Activity 31: Creating Class Methods and Using Information Hiding

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.

Activity 32: Overriding Methods

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.

Activity 33: Practicing Multiple Inheritance

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.

Chapter 8: Modules, Packages, and File Operations

Activity 34: Inspecting Modules

Solution:

  1. Inspect the resources defined in the itertools library by using the dir()
    function:

    >>> 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']

  2. Use the help() function to read about how to use the itertools library:

    >>> 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

Activity 35: Listing the Resources Defined in a Package or Module

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)

Activity 36: Using Resources in a Module

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

Activity 37: Performing File Operations

Solution:

with open("myfile.txt", 'w') as f:

f.write("I love Python")

Activity 38: Working with Files

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.

Chapter 9: Error Handling

Activity 39: Identifying Error Scenarios

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

Activity 40: Handling Errors

Solution:

import random

try:

print(random.randinteger(1,10))

except AttributeError:

print("Oops! Something went wrong")

Activity 41: Creating Your Own Custom Exception Class

Solution:

class RecipeNotValidError(Exception):

def __init__(self):

self.message = "Your recipe is not valid"

try:

raise RecipeNotValidError

except RecipeNotValidError as e:

print(e.message)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.70.21