Python for Beginners

808 162 815KB

English Pages 231

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Python for Beginners

Table of contents :
INDEX......Page 2

Citation preview

Python for Beginners A smarter way to learn Python and remember it longer Arthur T Brooks

Contents

INTRODUCTION CHAPTER ONE FIRST THINGS FIRST CHAPTER TWO VARIABLES AND VARIABLE RULES CHAPTER THREE STRINGS AND METHODS CHAPTER FOUR OPERATIONS WITH NUMBERS CHAPTER FIVE THE USE OF COMMENTS CHAPTER SIX OPERATIONS WITH LISTS CHAPTER SEVEN FURTHER OPERATIONS WITH LISTS CHAPTER EIGHT WORKING WITH LOOPS CHAPTER NINE WORKING WITH IF STATEMENTS CHAPTER TEN OPERATIONS INVOLVING DICTIONARIES CHAPTER ELEVEN NESTING DICTIONARIES AND LISTS CHAPTER TWELVE OPERATIONS INVOLVING USER INPUT AND WHILE LOOPS CHAPTER THIRTEEN OPERATIONS USING DEFINED FUNCTIONS

CHAPTER FOURTEEN OPERATIONS INVOLVING CLASSES CHAPTER SIXTEEN OPERATING WITH FILES CHAPTER SEVENTEEN MANAGING ERRORS WITH EXCEPTIONS CHAPTER EIGHTEEN HOW EVERYTHING COMES TOGETHER IN PROJECTS CONCLUSION ANSWERS TO THE EXERCISES INDEX -More Python books by Arthur T. BrooksPython for Beginners. Learn Data Science the Smart Way http://www.amazon.com/dp/B085RNT2C8

Copyright 2020 by Arthur T. Brooks - All rights reserved.

The following eBook is reproduced with the goal of providing information that is as accurate and reliable as possible. The recommendations suggestions contained in these pages are solely for entertainment purposes.

This declaration is deemed fair and valid by both the American Bar Association and the Committee of Publishers Association and is legally binding throughout the United States. Furthermore, the transmission, duplication or reproduction of any of the following work in any form (including specific information) is illegal. This extends to creating a secondary or tertiary copy of the work. No record copy of this work can me produced without with the express, written consent from the publisher. All additional rights reserved. The information in the following pages is broadly considered to be a truthful and accurate account of facts and, as such, any inattention, use or misuse of the information in question by the reader will render any resulting actions solely under his/her purview. There are no instances in which the publisher or the original author of this work can be deemed liable for any hardship or damages that may befall them after undertaking information described herein. Additionally, the information in the following pages is intended only for informational purposes and should thus be regarded as universal. As befitting its nature, it is presented without assurance regarding its prolonged validity or interim quality. Trademarks that are mentioned are done without written consent and can in no way be considered an endorsement from the trademark holder.

INTRODUCTION Python is one of the simplest programming languages in existence today. Although you may be trying to learn it for the first time, it is not necessarily that new. It was created in the 1980s by Guido van Rossum. Since then, notable companies like Yahoo, Facebook and Google have been using the language. Its advantage over other programming languages is its simplicity which the enables those who are venturing into programming for the first time to learn quickly and execute projects. Apart from this, highly experienced programmers also find the language handy in the daily practice of their art. What this Book is for and What You Can Expect to Learn This is a high quality, easy to understand, clear and concise non-technical, guidebook on how to learn Python in 5 days. You are not just going to learn how to code using Python, but how to understand actual Python itself. Apart from knowing Python code, you will be able to understand the way Python works which will enable you to use your creativity to achieve unlimited innovative tasks. It is written in a manner that anyone, even a complete novice can learn and understand how to use Python in real-life situations. It is structured from the simplest and shortest operations, introducing the more advanced parts of the language only after you have become familiar with the basic concepts. At the end of the book, you will realize that you have, without any stressful

self-exertion, become able to not only code in Python, but also think the way Python thinks. How to Use this Book If you follow this book faithfully, 5 days may even be too much time for you to spend for you to have a working knowledge of Python. However, we recommend that you follow the 5-day plan in order to maximize what you are learning by taking the extra time to properly digest the content. To make the most out of this book, study four chapters each day for the first three days, and three chapters each for the remaining two days. There are only eighteen chapters. Each chapter is short, straightforward and easy to understand, with examples to illustrate the lessons. At the end of each chapter, there is a chapter summary which recaps what you have learned in that chapter. More importantly, there are exercises at the end of each chapter to enable you try your hand on what you have just learned and make it stick in your mind. The examples and exercises in this book are based on real-life work situations which will give you a solid foundation on which to build upon. These initial applications are designed to ease you in gently, giving you the confidence and knowledge to kickstart you in the world of programming. Now this is not a book ‘about’ Python. Instead, it is a Python book. What is the difference? A book about Python will tell you a lot about Python and may be even explain just about everything that exists about Python. But you can finish a book about Python and not be able to use the language. On the contrary, this is a Python book which teaches you how to understand and use Python. That is the important difference. It is a practical manual for learning how to work in Python effectively. To help achieve this goal, it is strongly advised that you download Python 3 and the recommended text

editor and install them on your system before proceeding to the rest of the book. How to do this is covered in chapter one of the book. You learn Python and most other things in life by doing them. The essence of this guide is to enable you not just read along, but work along with the book. You can of course simply read the codes and just believe that they will do what the book says the codes will do. But a better way to learn is to actually write out the code in your text editor and run it to see whether what the book says about it is true. Secondly, as you write the code yourself, you will realize that there are certain aspects of the code like spacing, indentation, punctuation and so on, that you did not really notice at a glance but which can affect your outcome tremendously. You should, therefore, apply your hand to the task yourself and continue to practice often. It’s true what you were told, practice really does make perfect. At the end of this book, there are answers to the exercises found in each chapter. Do not rush to go and check the answers. Instead, try hard to get the required result by yourself first. The beautiful thing about this language is that if you write the correct code, you will know because it will produce the desired output. While these exercises and examples are written to cover as much as possible of what you have learned, do not limit yourself to them. Go beyond them. Think of as many real-life problems as you can imagine and write codes to solve them. It’s an entertaining exercise which let’s you understand and acknowledge your skills and development.

How the Book is formatted Codes are not necessarily eye-friendly. This is because they contain a mixture of symbols, letters and even numerical figures. To make it easier for your peepers as you read this book, the codes are written in a different

font type from the one used in the body of the book. It is also written in blue color. The output is written in the same font type as the code and bolded in orange color. Again, as you go through the book, you will realize that we are building progressively on what was learned previously. As a result, sometimes it is necessary to repeat the code in the previous example or chapter with only a few modifications here and there to achieve the current result. Where this is the case, the repeated code is colored green just to help you distinguish it from whatever is new. Thanks for buying this book. I really do hope that you enjoy it and it inspires you. If you do feel that you have gained real value from it then please take two minutes to leave me an honest review by clicking below. http://www.Amazon.com/gp/customer-reviews/write-a-review.html? asin= B07Y8R23CF It’s quick and easy and it will help others decide if they too could benefit from the book. Thanks in advance. I will soon be releasing more high-quality Python related books which I will offer those on my list either free or at a steep discount for the first 24 hours. Sound interesting? Join us here!

CHAPTER ONE

FIRST THINGS FIRST In this chapter, we are going to go through a few preliminary preparations that need to be put in place for you to be able to learn python quickly and successfully. We assume you already have a personal computer. You may or may not have python installed on it at the moment. So, we are going to start with installation. This tutorial is for Python 3 on a Windows operating system. Download and Install Python Visit python’s website on www.python.org/downloads to download python for Windows. You will see various links for the respective python versions. Identify the link to Python 3 and click on it. Automatically, the installer that is compatible with your version of Windows will be downloaded into your computer. Now that you have downloaded it, double-click on the file and follow the steps in the prompt to install Python 3.

Download and Install a Text Editor There are a number of text editors available to programmers using python. A text editor is what is otherwise called an Integrated Development Environment, IDE. It is a user-friendly environment that enables you to type in your codes easily, and which also makes it possible for you to testrun the code’s output in Windows command prompt screen. In this book, we will be using Geany. It is a simple text editor which contains everything that you need as a beginner learning to program in python.

To download Geany, go to www.geany.org and search for the setup.exe file. There are a number of versions that are available on the website. Download the most recent one and install by following the prompts.

Running Your Very First Python Program Now, start your program by opening Geany. You simply need to identify it in the list of programs on your computer and click on it. When it opens, save the empty program by a unique file name ending with the extension .py. Python as a programming language uses lower case letters. Just to make you stick with this fact early enough, type your file name in small letters. The important thing here is to ensure that whatever file name you type has a .py extension at the end. The purpose of the extension is to let Geany know that the content of this file will be a python program. Because of this, Geany will highlight the codes with different colors to make it easier for your eyes as you write the code. Your file can be something like python_work.py. By the way, you may want to create a new folder dedicated to saving all your python files. Now that the file is saved, you are set to write your very first program in python. Just type the code below: print(“Hello everyone!”) Now, run or execute your program by pressing the shortcut F5 on your keyboard or by clicking on Execute on the menu bar. You will see a terminal window appear, showing you the output of your program as contained below: Hello everyone!

Note that python operates by a very strict guideline of specificity. The program uses codes in lower case letters and if you alter this at any point, you will get an error message. Also, you can use the double (“) or single (‘) quotation marks. However, do not mix both types in one code statement. This, too, will give you an error message.

Chapter Summary In chapter one, you have learned how to download and install Python. Not only that, you have also learned how to download and install a text editor to enable you write and run Python codes. In the same chapter, you also learned how to run your very first code in Python.

Exercises 1. Go to the internet and conduct a brief research on the various sectors of human life in which Python is used today. This should stimulate your appetite and increase your determination to make a success of your journey in learning Python.

CHAPTER TWO

VARIABLES AND VARIABLE RULES A variable is an arbitrary name in Python to which a value or set of values are assigned. When a command is given to Python to with respect to a variable, Python executes that command on the values assigned to that variable. For example, in chapter one, we gave the command below to Python: print(“Hello everyone!”) And Python produced the following output: Hello everyone! We can introduce a variable, and assign “Hello everyone!” to it. Let our variable be greeting. After assigning a value to it, we will ask Python to print it. greeting = “Hello everyone!” print(greeting)

If you run this program, you are going to get the same output you got in chapter one: Hello everyone! What is happening is that Python reads the first line of code, and learns that the variable, greeting, refers to the value, “Hello everyone!” Therefore, wherever Python sees greeting, it understands that it is referring to “Hello everyone!” So, when Python reads the second line which is a command to print the variable, it simply prints the value attached to the variable. Variable Rules

Now, there is no boundary to what names you can use as your variables. However, there are a few things to keep in mind while creating variables. Ignoring these things will make Python give you error messages when you try to run a program. • Use only alphabets, numbers and underscores in your variable names. Also, do not begin a variable name with a number. Always begin with an alphabet or an underscore. • Do not use spaces in variable names. Instead, use underscores to separate space words that make up a variable name. • Do not enclose your variable names in quotation marks. Variable names stand on their own. • Do not use Python keywords and function names for your variable names. These are words which are already inbuilt into Python to serve specific programming purposes. Python does not allow you to use these words because using them as variables will confuse the program. • Make your variable names short and meaningful. As much as possible, let them carry enough meaning for anyone who can read and write to be able to guess exactly what they mean. This is important because you may be working with other programmers on the same project. They need to understand what you are writing. • Ensure that your variable name is spelled the same way everywhere. Python does not bother about the grammatical correctness of the spelling of your variable name. However, whatever you spell as your variable name has to be spelled the same way in all operations. If this is not done, Python will not be able to recognize the variable name and therefore, give you an error message.

• Be careful to define your variable names before using them subsequently in an operation. Notice that in the example above, we have defined the variable greeting as follows: greeting = “Hello everyone!” That is why Python recognizes greeting as a variable. Without first defining this variable, any attempt to execute a command on it will give an error message. Chapter Summary In chapter two, you have learned what variables are, and how to define them in Python. You have also learned a few rules to keep in mind while creating new variables. Now, you may undertake the exercises that follow. Exercises 1. Create a variable name using public school teachers and assign the following values to it: James, Bill, Andrew, Hillary. Now, ask Python to print your new variable. 2. Change the values you assigned to the variable name in the exercise above, and replace them with Fred, Todd, Wilson. Now, ask Python to print the variable a second time.

CHAPTER THREE

STRINGS AND METHODS In Python, a string is a value enclosed within quotation marks. This may be words or numbers. For example, the following are strings: “Football match,” and “32.” These quotation marks may be double or single. The only rule is to be consistent with which type you choose to use. A method is a specific effect that Python makes to a value. This effect alters the appearance of the value. In this chapter, we are going to use the following methods to effect certain changes to some string values: title, upper, and lower. Example 1: Lower Case to Title Case In this example, we are going to create a string variable, and use a method to change it from lower case to title case. Title case means the first letters of each word are capital letters. Here we go. We will create a variable, official, and assign the string value, “high commissioner,” to it. official = “high commissioner” Next, we will use the title() method, to render this value in the title case. print(official.title()) Run this code now and let us see what you get. You should get the output below: High Commissioner Example 2: Title Case to Upper Case In this example, we are going to use another method, upper, to change the value attached to our variable from title case to upper case. Upper case

means all the letters in the value will be capital. We type in the code below: official = “high commissioner” print(official.upper())

Run the code above and let us see what you get. It should give you the output below: HIGH COMMISSIONER Example 3: Upper Case to Title Case In this example, we will alter the value assigned to our variable a bit by making it upper case or title case. Next, we will yet use another method, lower, to return the value to the lower case. Lower case means all the letters are small. We will use the code below: official = “HIGH COMMISSIONER” print(official.lower())

After running the code, you should get the output below: high commissioner How to Join or Concatenate Strings Often, circumstances arise when a programmer needs to join a couple of strings together. This is called concatenation. Usually, the programmer creates these strings with separate variable names, and join them while displaying in Python. Consider the examples below. Example 4: Joining a Title and First Name

In this example, we are going to create the variables, title, last name and salutation. After this, we are going to print the last variable, salutation. We will use the code below: title = “Professor” last_name = “McCaine” salutation = title + “ ” + last_name print(salutation)

After running the above program, you will get the output below: Professor McCaine Example 5: Simple Salutation Message In this example, we are going to go further and print a message using the variable, salutation. We will use the program below: title = “Professor” last_name = “McCaine” salutation = title + “ ” + last_name print("Good afternoon, " + salutation + ".")

After running the program above, you will get the output below: Good afternoon, Professor McCaine. Example 6: Whole Message in a Variable In this example, we will go a little further and save the greeting above into a variable. This will make it much easier to ask Python to print the greeting.

The program for this will look like this: title = "Professor" last_name = "McCaine" salutation = title + " " + last_name greeting = "Good afternoon, " + salutation + "." print(greeting) After running the program above, you will still get the output below: Good afternoon, Professor McCaine. Chapter Summary In chapter three, you have learned about strings and methods. You now know that strings are values that are enclosed in quotation marks. You also know that methods are effects that Python can add to strings. In addition, you have learned how to concatenate strings. Now, attempt the exercises below.

Exercises 1. Create a string variable, name, and attach the value, catherine stone, to it. Now, use the upper, title, and lower methods to print it. 2. Create the following variables with their corresponding values: first_name (James)and last_name (Bull). Next, create a third variable full_name, which should be a concatenation of the first two variables. Then, ask Python to display full_name. 3. Ask Python to display this message, “My most attractive high school friend was” with full_name.

4. Repeat number 2 and 3 for three more of your high school classmates. When you print the message, it is going to help you appreciate that it is easier to make sentences using the names as coded than trying to remember every person’s names. 5. Create a new variable, message, which should contain the statement in 3 above. Now, ask Python to display it.

CHAPTER FOUR

OPERATIONS WITH NUMBERS There are several uses that numbers have in writing programs. In Python, numbers can be handled in a variety of ways. What determines how Python will handle a number is dependent on how the number is being used. That is, the purpose the number is supposed to serve. You can do simple mathematical operations such as addition (+), subtraction (-), multiplication (*) and division (/) in Python. Consider the following examples. Example 1: Addition, Subtraction, Multiplication and Division In this example, we are going to conduct simple mathematical operations on whole numbers otherwise called integers. Addition Enter the following program in your Geany text editor. print(4+5) When you run the above program, Python returns the output below: 5 . You can do this for any combination of whole numbers, and Python will still return the mathematical sum. Enter the following program and ask Python to display the sum. print(2+3+30+6) Python displays 41 which is the mathematical sum of the addition above. Subtraction Enter the following program in your Geany text editor. print(20-5) Python returns 15 which is the correct answer.

Multiplication Enter the following program to carry out an operation using multiplication. print(4*5) Python returns 20 which is the correct answer. Division Enter the following program to perform an operation using division. print(12/2) Python returns 6, which is the correct answer. Operations with Numbers and Words You will remember that in the section on strings, you learned that strings can either be texts or numbers enclosed in quotation marks. In life, situations abound where numbers and text are combined together in sentences. For example, consider the sentence below. I live on Number 25, James Stone Street. Enter the following program in an attempt to ask Python to display the sentence above, and see what the output will be. street_number = 25 print("I live on Number" + street_number + "," + "James Stone Street")

Python returns an error message, because it cannot concatenate integers (whole numbers) to strings. It can only concatenate string to strings or integers to integers.

To solve the problem above and still achieve what we set out to achieve, we must explain to Python that although 25 is an integer, we want it to function as a string value in this situation. To do this, we have to use the str() function. Now, consider the code below: street_number = 25 print("I live on Number " + str(street_number) + ", " + "James Stone Street") Notice that the str() function has enclosed the variable, street_number, in parentheses. This notifies Python that the enclosed variable is a string variable. Therefore, look what Python now prints in the output. I live on Number 25, James Stone Street You should not have any problems deciding whether the number you are including in a statement is a string or integer. Notice that this limitation only exists because you are trying to concatenate strings and integers together. You can still achieve the output above by entering the program below: print(“I live on Number 25, James Stone Street”) However, assume that you have a huge store of data containing several numerical values attached to several people, say, customers in a business corporation. Then your company asks you to compose a birthday message to each customer using their ages. It is going to be tough work, trying to go through the data store, searching for specific ages to include in the statement. Let us consider a hypothetical customer, Andrew, who is celebrating his 45th birthday. You will have to go through the records, identify that for

Andrew, the figure to be included in the birthday message, is 45. So you print a message for him using the code shown below: print(“Happy 45th birthday, Andrew”) This is going to be hectic, going through the entire customer database to identify what birthday anniversary each customer is celebrating. On the contrary, assume that each customer’s current age was coded in a variable designed to contain their first name and “age.” For Andrew, the variable will be andrew_age. To print a message for Andrew on his birthday, you will simply enter the code below: andrew_age = 45 print("Happy " + str(andrew_age) + "th " + "birthday, Andrew!")

Python returns the following output. Happy 45th birthday, Andrew! Again, while this is no doubt helpful, it is still tedious because you have to know the customers’ first names. Now, suppose the company went a step higher and coded each customer’s first name too. Let us assume, Andrew is the first customer, so his name is coded as customer_1. The program for his birthday message will now read as shown below. customer_1 = "Andrew" customer_1_age = 45 print("Happy " + str(customer_1_age) + "th " + "birthday, " + customer_1 + "!")

Now, because the customers’ names and ages were coded systematically, you can compose a message for each customer without having to look up what their name or age is. This will make the whole task a lot easier. A few things to note, however, include the fact that Python is very strict with its language. Always be consistent with your use of quotation marks, parentheses, and variable names. Any changes in these that contradict Python’s rules will give you an error message. Chapter Summary In this chapter, you have learned how to perform basic mathematical operations such as addition, subtraction, multiplication and division, in Python. You have also learned how to join or concatenate numbers and texts in a single sentence. To entrench this knowledge, attempt the exercises below. Exercises 1. Write out a Python program to perform the following mathematical operations: a). 6+10 b). 50-12 c). 16*2 d). 32/8 2. You are a customer care representative of your company. The following customers have their birthday anniversaries today, and your company has asked you to compose birthday messages to them, specifically mentioning their ages and names. First, create systematic variables containing their

names and ages, and secondly, write the Python code for displaying each customer’s message. a). Andrew, 50 d). Annie, 18

b). James, 45

c). Candy, 33

CHAPTER FIVE

THE USE OF COMMENTS Most of the programs we have written so far are simple and selfexplanatory. However, as we go forward, you will realize that certain programs are perhaps not quite as straightforward. After playing with loads of codes, you may not be sure to remember exactly what you were trying to achieve and what steps you took to achieve it while you were coding. This is especially common when you have been away from the project for a while. Instead of spending precious hours sweating over the meaning of what you coded yourself, there is a way to keep a record of your coding process. The above is just one scenario in which a programmer can be in need of help while going through loads of codes. Another scenario often arises when different programmers are working on one project. They may not be able to automatically tell exactly what one programmer was thinking when he wrote a particular code. This could create some difficulty, requiring unnecessary physical communication between the programmers and delaying the progress of the project. To solve this challenge, there is the provision for comments. Comments are the programmer’s notes about what he is trying to do or the steps he is following in doing it. Comments are in English and do not have to follow any Python syntax rules. Python does not try to run comments or show them in the output. Comments are indicated by the hash sign (#) at the beginning. Enter the code below in the text editor and let us see the output: #For large numbers of customers, it is easier to use the code below: customer_1 = "Andrew"

customer_1_age = 45 print("Happy " + str(customer_1_age) + "th " + "birthday, " + customer_1 + "!")

Python still gives the same output as given in chapter four. There is no particular rule regarding how many comments to write when writing a program. However, whenever you are in doubt whether it is necessary to write a comment or not, you probably should write one. If you are working on a project with a considerable length of code, try to write comments at each major turn to explain how you arrived there, and how you intend to proceed. As a matter of necessity, if you had some trouble figuring out your way around a particular programming task, it will help you and your collaborators a lot if you describe in the simplest terms how you eventually succeeded. As a rule, it is better to write too many comments than to write too little. In the case of too many comments, the excess comments can be easily deleted, but new comments cannot be so easily written after the program has been written and forgotten. Chapter Summary In this chapter, you have learned about the provision for writing comments in Python. You have also seen that comments are an important way of remembering the various approaches a programmer took while working on a particular project.

Exercise You are a customer care representative of your company. The following customers have their birthday anniversaries today, and your company has

asked you to compose birthday messages to them, specifically mentioning their ages and names. First, create systematic variables containing their names and ages, and secondly, write the Python code for displaying each customer’s message. Include clear comments at the beginning of the program, explaining what you want to achieve, and how you are going to achieve it. a). Andrew, 50 d). Annie, 18

b). James, 45

c). Candy, 33

CHAPTER SIX

OPERATIONS WITH LISTS One of the powerful features you will find in Python is the provision of lists. A list is a group of items that are related by certain features. Python has an amazing capacity to accommodate lists, whether the items on a list are just a few or significantly huge in number. You can make a list of almost anything you want. It can be a list of your classmates’ names, your favorite television shows, the names of your family members, the cities in which you have lived, and so on. It is not compulsory for the items on your list to be similar. Whatever you choose to include in a list is purely your discretion. If you look at the code for a list, you will realize that a list is essentially a variable whose values are more than one, separated by commas, and are enclosed in square brackets. Consider the list of your classmates’ names below. classmates_names = ["Jane", "Francisca", "Ann", "Philips"] print(classmates_names)

If you run the program above, Python will return the list in the square brackets as shown below. [‘Jane’, ‘Francisca’, ‘Ann’, ‘Philips’] Example 1: Displaying Specific Items on a List This output is not really the goal of grouping items in a list. Moreover, when you group items in a list, you want them to be there so that you can more easily refer to them whenever you choose to.

Python understands this too. That is why there is a provision for dealing with specific items on a list. Suppose you want to display just an item on the list of your classmates’ names above. All you need to do is to write a code that specifies to Python the position or index of the item. Consider the program below. classmates_names = ["Jane", "Francisca", "Ann", "Philips"] print(classmates_names[0])

Python goes to the list of your classmates’ names and prints out the first name on it as shown below. Jane Notice that the code for printing the particular item contains square brackets in which the position of the desired item is stated. Python begins counting the position of the items from zero. The code below prints the items on the list at the respective positions. classmates_names = ["Jane", "Francisca", "Ann", "Philips"] print(classmates_names[0]) print(classmates_names[1]) print(classmates_names[2]) print(classmates_names[2])

The output is as follows: Jane Francisca

Ann Philips Sometimes a list can be so lengthy that you do not know the number of items on it, and yet desire to print an item on a certain position from the last. For example, in the list above, suppose you wish to print the name of your classmate that is second to the last. Python has a code for this too. To print the last item on the list, enter the code below. classmates_names = ["Jane", "Francisca", "Ann", "Philips"] print(classmates_names[-1])

When you run the code above, Python returns Philips which is the last name on the list. You can also use this code to display the items on a list in the reverse order in which they originally appear. Carefully consider the code below and the output. classmates_names = ["Jane", "Francisca", "Ann", "Philips"] print(classmates_names[-1]) print(classmates_names[-2]) print(classmates_names[-3]) print(classmates_names[-4])

When you run the code, Python returns the names on the list in a reverse order as shown below. Philips Ann

Francisca Jane Wider Application of Items on a List The essence of coding items on a list in Python is not just to get an alternative way of displaying them. Traditionally, if you want to make a list, you simply write it out. And if you want to refer to a particular item on the list, you go through it, identify the item and write it out. However, the longer a list, the more difficult it becomes to go through it every time you want to work with an item on it. This is where the advantage of having a prepared list in Python comes in. Python only requires you to state the position of the item on the list and does the job of identifying the item for you. This has further application in real life. Suppose you are the examination officer of your school, and the school wants you to print congratulatory statements to the students, mentioning each student by name and stating their position in the end-of-year examination. The mechanical way to do this will be to compose a template statement, and then go through the list, identifying each student by name and position in class, and returning to complete the statement with the details. This is, no doubt, tasking. However, suppose that the students’ names have been arranged on a list in Python according to their performance in the class, from the first position to the last. All you need to do now is to write a program asking Python to display a congratulatory message and fetch the name of the student concerned from the list. This way, you only specify the position, while Python provides the real name of the affected student. Consider the code below:

classmates_names = ["Jane", "Francisca", "Ann", "Philips", "Andrew", "James", "Fred"] print("Congratulations" + "," + classmates_names[0] + ". " + "You are the top of the class" + ".")

When you run this code, Python returns the congratulatory message below: Congratulations, Jane. You are the top of the class. Now, without bothering about which name is in which position, I can still print a congratulatory message to each student, mentioning the student’s name and position. Consider the code below for more of the students. classmates_names = ["Jane", "Francisca", "Ann", "Philips", "Andrew", "James", "Fred"] print("Congratulations" + "," + classmates_names[0] + ". " + "You are the top of the class" + ".") print("Congratulations" + "," + classmates_names[1] + ". " + "You are the second in the class" + ".") print("Congratulations" + "," + classmates_names[2] + ". " + "You are the third in the class" + ".") print("Congratulations" + "," + classmates_names[3] + ". " + "You are the fourth in the class" + ".") print("Congratulations" + "," + classmates_names[4] + ". " + "You are the fifth in the class" + ".")

Before you run the code above, notice that everything is essentially the same in the syntax except the index of the items which has increased progressively from zero to four, and the second part of the sentence which is altered accordingly from top to fifth. Run the code now, and see what Python returns as shown below. Congratulations, Jane. You are the top of the class. Congratulations, Francisca. You are the second in the class. Congratulations, Ann. You are the third in the class. Congratulations, Philips. You are the fourth in the class. Congratulations, Andrew. You are the fifth in the class.

Example 2: Adjusting the Items on a List After compiling your list in Python, suppose you want to adjust it a little. From the example above, suppose you realize that the student named Jane was not actually the top of the class. Rather, Philips was. You may wish to remove Jane from that position and return Philips there. In this case, let us assume there was a swap, and Jane was actually the fourth. To achieve this, you use the code below: classmates_names = ["Jane", "Francisca", "Ann", "Philips", "Andrew", "James", "Fred"] classmates_names[0] = "Philips" classmates_names[3] = "Jane" print(classmates_names)

From the code above, you will notice that Python has been instructed to put Philips in the first position and Jane in the fourth position. Now, run the code and see the output. [‘Philips’, ‘Francisca’, ‘Ann’, ‘Jane’, ‘Andrew’, ‘James’, ‘Fred’] Example 3: Including New Items on a List Suppose the examination results displayed above were not the complete result for the class, and you want to add more students to it. You can do this in Python using the append() method. This method, adds the new item at the end of the list. Now, let us add two more students to the list. classmates_names = ["Jane", "Francisca", "Ann", "Philips", "Andrew", "James", "Fred"] classmates_names.append("Chris") classmates_names.append("Alex") print(classmates_names) You will notice that the names of the new students are enclosed in the brackets following the append() method. Notice also, that the names were added individually. This is because the method takes only one item per time. If you enclose more than one item in the method, Python will return an error message. Now, let us run the code and see the output. [‘Philips’, ‘Francisca’, ‘Ann’, ‘Jane’, ‘Andrew’, ‘James’, ‘Fred’, ‘Chris’, ‘Alex’] Apart from adding items to the list at the end, you can also add items to the list at whatever position you choose. To do this, you need to use the insert() method. Let us now add a new student, Tony, to the list at position 6.

classmates_names = ["Jane", "Francisca", "Ann", "Philips", "Andrew", "James", "Fred"] classmates_names.insert(5, "Tony") print(classmates_names) Run the code and see what output Python gives. [‘Philips’, ‘Francisca’, ‘Ann’, ‘Jane’, ‘Andrew’, ‘Tony’, ‘James’, ‘Fred’] Example 4: Removing Items from a List Sometimes, instead of inserting a new item on the list, you want to remove an item from the list. This can be done using the del statement. From our list above, let us remove the student, Ann. Enter the code below and run it. classmates_names = ["Jane", "Francisca", "Ann", "Philips", "Andrew", "James", "Fred"] del classmates_names[2] print(classmates_names) Python returns the output below. [‘Philips’, ‘Francisca’, ‘Jane’, ‘Andrew’, ‘James’, ‘Fred’] The del statement is one way to remove an item from a list. When you use this statement to remove an item, you can no longer have access to that item. In other words, that item is gone permanently. However, there may be situations when you desire to use the item removed to form another list, or compose a message. In such situations, the pop() method is used. With this method, you can remove the last item on the list. Now, let us remove Fred from the list above. Enter the following code and run it.

classmates_names = ["Jane", "Francisca", "Philips", "Andrew", "James", "Fred"] print(classmates_names) popped_names = classmates_names.pop() print(classmates_names) print(popped_names) First, the list of classmates’ names is defined and printed. Next, a new variable, popped_names, is created to contain the names that will be popped, classmates_names.pop(). Then, the list of classmates’ names is printed again to show that the last name has been popped. Finally, the popped_names have been printed to show that the name is still accessible after having been popped. See the output below. [‘Philips’, ‘Francisca’, ‘Jane’, ‘Andrew’, ‘James’, ‘Fred’] [‘Philips’, ‘Francisca’, ‘Jane’, ‘Andrew’, ‘James’,] Fred In other circumstances, you may want to pop an item in a different position on the list. In that case, you need to specify which position the item occupies. To pop a student from the list above, enter the code below: classmates_names = ["Jane", "Francisca", "Philips", "Andrew", "James", "Fred"] print(classmates_names) popped_names = classmates_names.pop(1) print(classmates_names) print(popped_names)

Python gives the output below. [‘Philips’, ‘Francisca’, ‘Jane’, ‘Andrew’, ‘James’, ‘Fred’] [‘Philips’, ‘Jane’, ‘Andrew’, ‘James’, ‘Fred’] Francisca Sometimes, you may not know the exact position of an item on the list. You may, however, know the item which you want to remove. There is a provision in Python for you to still remove the item. This is done using the remove() method. For example, you may want to remove Philips from the list above. Enter the following code. classmates_names = ["Jane", "Francisca", "Philips", "Andrew", "James", "Fred"] print(classmates_names) classmates_names.remove("Philips") print(classmates_names) When you run the code, Python gives the output below. [‘Jane’, ‘Francisca’, ‘Philips’, ‘Andrew’, ‘James’, ‘Fred’] [‘Jane’, ‘Francisca’, ‘Andrew’, ‘James’, ‘Fred’]

Chapter Summary In this chapter, you have learned how to perform operations involving lists. You have learned how to create lists, add items to the lists and remove items from the lists using various methods. Now, practice with these exercises in order to establish what you have learned.

Exercises 1. Prepare a list of 12 items and print them both in the original order and in the reverse order. 2. Using the list above, perform the following operations: append, insert, del, pop, and remove. 3. You are employed in the prison service of your country to help with keeping clear records of the prisoners. The particular task before you now is to work with a list of ten prisoners. Each time a prisoner is granted parole, you are required to remove his name from the list and include it in the new list of those granted parole. Using pop(), write a program that achieves this.

CHAPTER SEVEN

FURTHER OPERATIONS WITH LISTS Example 1: Sorting a List Alphabetically Supposing you wish to present the items on a list in alphabetical order. If you wish to make this change permanent, you can use the sort() method. This time, we will compile a list of six countries of the world and sort them in alphabetical order. Consider the code below. countries = ["United States", "Great Britain", "Russia", "Japan", "South Korea", "Nigeria"] print(countries) countries.sort() print(countries) Python returns the output shown below. [‘United States’, ‘Great Britain’, ‘Russia’, ‘Japan’, ‘South Korea’, ‘Nigeria] [‘Great Britain’, ‘Japan’, ‘Nigeria’, ‘Russia’, ‘South Korea’, ‘United States’] Next, we will sort these countries in the reverse alphabetical order using the steps below. countries = ["United States", "Great Britain", "Russia", "Japan", "South Korea", "Nigeria"] print(countries) countries.sort(reverse=True) print(countries)

Python returns the output below. [‘United States’, ‘Great Britain’, ‘Russia’, ‘Japan’, ‘South Korea’, ‘Nigeria] [‘United States’, ‘South Korea’, ‘Russia’, ‘Nigeria’, ‘Japan’, ‘Great Britain’] To sort the items alphabetically but only temporarily, you can use the sorted() function. After using the function, the list will display in the alphabetical order, but you can still request the original list and get it in its original arrangement. Use the code below to achieve this. countries = ["United States", "Great Britain", "Russia", "Japan", "South Korea", "Nigeria"] print(countries) print(sorted(countries)) print(countries) Python returns the output shown below. [‘United States’, ‘Great Britain’, ‘Russia’, ‘Japan’, ‘South Korea’, ‘Nigeria] [‘Great Britain’, ‘Japan’, ‘Nigeria’, ‘Russia’, ‘South Korea’, ‘United States’] [‘United States’, ‘Great Britain’, ‘Russia’, ‘Japan’, ‘South Korea’, ‘Nigeria] Notice that the first and last lists are arranged in the same order, while the second one is arranged alphabetically. Example 2: Reversing a List

You can use the reverse() method to reverse whatever order the items on a list appear. This method differs from the one used with sort() above because it does not re-arrange the items in alphabetical order. Instead, it simply reverses whatever order the original list appeared in. Now, let us reverse the original list of countries we made above using the code below. countries = ["United States", "Great Britain", "Russia", "Japan", "South Korea", "Nigeria"] print(countries) countries.reverse() print(countries) The output is shown below. [‘United States’, ‘Great Britain’, ‘Russia’, ‘Japan’, ‘South Korea’, ‘Nigeria’] [‘Nigeria’, ‘South Korea’, ‘Japan’, ‘Russia’, ‘Great Britain’, ‘United States’]

Example 3: Length of a List To determine the length of a list in Python, you can use the len() function. Let us determine the length of the list above. Enter the code below and run it. countries = ["United States", "Great Britain", "Russia", "Japan", "South Korea", "Nigeria"] print(len(countries)) Python returns 6.

Chapter Summary In this chapter you have learned additional operations using lists, such as sorting a list, reversing a list, and determining the length of a list. Exercise Draw up a list of five of your favorite high school teachers. Sort this list alphabetically both permanently and temporarily, and reverse it, using Python language.

CHAPTER EIGHT

WORKING WITH LOOPS In real life situations, a list can be quite long; indeed, several times longer than the ones we have been using so far. You may be required to perform the same action with all the items on the list. Instead of writing a code for each of these items, you can use the loop function to ask Python to perform these repeated actions on your behalf. Example 1: Looping through a List For example, we will loop through the list of countries we compiled above, and print each country on that list, using the code below. countries = ["United States", "Great Britain", "Russia", "Japan", "South Korea", "Nigeria"] for country in countries: print(country) First, we provide a list of countries as shown above. Next, we instruct Python, that for every country found in the list of countries, Python should print it. What Python does here is to loop through the entire list of countries, and print a country, one at a time, until it has exhausted the list. The output is shown below. United States Great Britain Russia Japan South Korea

Nigeria

Example 2: Automating Tasks with a Loop Using the loop, you can ask Python to perform repeated tasks on the items on a list. For example, supposing your list is a list of students who have been offered admission into your university. You want to display to each of them a congratulatory message bearing their name when they check their admission status on the school portal. Note that in this case, the congratulatory message is the same. Only the name of the student changes. You can use the code below. successful_students = ["Andy", "Tom", "Tony", "Susan", "Annie"] for student in successful_students: print("Congratulations" + "," + " " + student + "." + " " + "Welcome to Abraham Lincoln University" + ".") First, we defined the list of successful students. Next, we asked Python to identify the names that are in that list. Then we asked Python to print a congratulatory message to each of the students identified in the list of successful students. See the output below. Congratulations, Andy. Welcome to Abraham Lincoln University. Congratulations, Tom. Welcome to Abraham Lincoln University. Congratulations, Tony. Welcome to Abraham Lincoln University. Congratulations, Susan. Welcome to Abraham Lincoln University. Congratulations, Annie. Welcome to Abraham Lincoln University. This is much faster than if you were to code a message for each student.

If you observe the code above, you will notice that each line following the for loop is indented. The effect of this indentation is that whatever you ask Python to do in those lines will be applied to all the items in the list. To execute other commands that are not general to the entire group, go to the next line, and close up the indentation. Consider the code below. successful_students = ["Andy", "Tom"] for student in successful_students: print("Congratulations" + "," + " " + student + "." + " " + "Welcome to Abraham Lincoln University" + ".") print("We love you.") print("Abraham Lincoln University: Seat of Wisdom") Here, we have included one more statement in the next indented line under the for loop. This statement therefore applies to all the students. However, on the last line, there is no indentation, hence the statement is printed alone. The output is shown below. Congratulations, Andy. Welcome to Abraham Lincoln University. We love you. Congratulations, Tom. Welcome to Abraham Lincoln University. We love you. Abraham Lincoln University: Seat of Wisdom

Chapter Summary

In this chapter, you have learned how to perform operations using a for loop, which enables Python to perform repetitive actions on all the items on a list. Exercise You are organizing a birthday celebration for your son, Tom. You want to send birthday invitations to three of his friends. 1. Prepare a list of his three friends, and print it using the for loop function. 2. Using the for loop function, print this invitation for them addressing them by their names: “Tom invites you to his birthday celebration.” 3. At the end of the invitation message to them, print one general message that says, “You are all invited.”

CHAPTER NINE

WORKING WITH IF STATEMENTS In programming, there are moments when you want Python to take certain actions only in the setting of certain circumstances. With the use of the if statement, you can instruct Python to take specific actions under particular situations. Example 1: Selective Conversion to Upper Case Suppose you have a list of countries of the world which you want to print. Since names of countries are proper nouns, they should be spelled in title case. However, since entries in Python are often made in lower case, you want to perform an operation that will convert the entire list to title case. The problem is that in your list, the United States of America is abbreviated as usa, which should be written in upper case and not lower or title case. You can use the if statement to convert usa to upper case and the rest to title case. countries = ["germany", "usa", "brazil", "uk", "argentina"] for country in countries: if country == "usa": print(country.upper()) else: print(country.title()) Python gives the output below. Germany USA

Brazil Uk Argentina Notice, however, that there is another country in the list that is also abbreviated. But because we did not instruct Python concerning it, it is still written in title case. We will now add the if statement to cover the next abbreviated country also. The code will now look as shown below. countries = ["germany", "usa", "brazil", "uk", "argentina"] for country in countries: if country == "usa": print(country.upper()) if country == "uk": print(country.upper()) else: print(country.title()) The output will now include the uk in upper case as shown below. Germany USA Brazil UK Argentina Example 2: Tracking a Criminal

Suppose that you are an employee of an investigative agency. A crime has occurred and you have taken in a couple of criminal_suspects whom you plan to screen. Let’s say you are looking for fingerprints that match those of a notorious criminal called Fred. You want to write a program in Python that performs this screening. Study the code below. criminal_suspects = ["Bill", "Bull", "Billy"] for criminal in criminal_suspects: if criminal_suspects == "Fred": print("Detain for further investigations.") else: print("Release from detention.") Notice that we are using the for loop to search through the fingerprints of the criminal_suspects for the one that matches that of Fred. Now, in addition to the if statement, we have made Python to display a message that alerts us to detain a suspected criminal for further investigations if the suspect’s finger print matches that of Fred. However, where the suspect’s finger print does not match that of Fred, Python will alert us to release the suspect from detention. Now, look at the output below. Release from detention. Release from detention. Release from detention. We can infer from this output that none of the fingerprints of the suspects matched that of Fred. Example 3: Using the Inequality Sign

We can also use the inequality sign to achieve the same outcome as shown in the code below. criminal_suspects = ["Bill", "Bull", "Billy"] for criminal in criminal_suspects: if criminal != "Fred": print("Release from detention immediately.") The output produced by Python is shown below. Release from detention immediately. Release from detention immediately. Release from detention immediately.

Example 4: Addressing Each Suspect by Name Again, by looking at the list of suspected criminals, we can infer that the statements in the output refer to Bill, Bull and Bully respectively. However, we can make it easier to trace which statement refers to which suspect. To achieve this, we are going to write a code that will enable Python to effectively address each suspect by name. Carefully study the code below. criminal_suspects = ["Bill", "Fred", "Billy"] if criminal_suspects[0] == "Fred": print("Detain" + " " + criminal_suspects[0] + " " + "for further investigations.") else:

print("Release" + " " + criminal_suspects[0] + " " + "from detention.") if criminal_suspects[1] == "Fred": print("Detain" + " " + criminal_suspects[1] + " " + "for further investigations.") else: print("Release" + " " + criminal_suspects[1] + " " + "from detention.") if criminal_suspects [2] == "Fred": print("Detain" + " " + criminal_suspects[2] + " " + "for further investigations.") else: print("Release" + " " + criminal_suspects[2] + " " + "from detention.")

Note the following: a). This code is longer than the one in Example 3. This is because, in that example, we did not require Python to write the message, mentioning each suspect by name. b). The for loop has been removed. c). The second suspect on the list has finger prints that match those of Fred, hence for the sake of establishing uniformity in Python, he too is called Fred.

d). We have applied the if statement to each suspect individually, and combining this with the index of each suspect, we are able to print a personalized statement about the suspect. Now, consider the output that Python gave as shown below. Release Bill from detention. Detain Fred for further investigations. Release Billy from detention.

Using the if-elif-else Sequence Although the if statement you just learned above is no doubt very useful, life is often more complex than that. Sometimes, situations arise which present three alternatives which are to be available only in a sequence. For instance, you may want to ask Python to print separate messages to three different groups. The if-elif-else sequence is used to achieve this. Example 5: Separate Camping Instructions to Males and Females Let us assume you are organizing a weekend gathering with separate camping facilities for males, females and children. You want to write a program that gives specific information depending on which group the person using it belongs to. Now, note that unless Python is able to decide the exact group of the user, it may print the wrong set of instructions. In real life, this can be quite costly. Suppose in this example, that such a mix up happens. It means that some males will be misdirected to the females’ boarding facility and vice versa. In a commercial setting, benefits may be paid into the accounts of the wrong category of customers or

employees. In this example, we will use the if-elif-else sequence to do this. Study the code below. gender = "male" if gender is "male": print("Hi. Welcome to our weekend picnic. Your room is in Block H.") elif gender is "female": print("Welcome dear. Your room is in Block F.") else: print("Welcome sweetie. One parent should accompany you to Block A.") Note the following in the code above: a). The variable, gender, is the gender of the participant at the weekend picnic. b). The rest of the code has three different messages but will print only one at the end depending on the gender of the participant. The participant can only have one response to the question of gender. c). Python executes this command sequentially. First, it takes the gender of the participant and begins to check what message is appropriate for that gender. In this example, the gender is male. Python moves to the second command that tells it what to do with the male gender, which is to print a certain message. d). Since this gender is male, Python prints the message, and does not bother to go any further down the code for anything else. So it produces the output below.

Hi. Welcome to our weekend picnic. Your room is in Block H. e). However, if Python did not find a message for the male gender in the first part of the code, it would have continued farther down until it found the message.

Example 6: Female Participant We will now change the gender of the participant to female. gender = "female" if gender is "male": print("Hi. Welcome to our weekend picnic. Your room is in Block H.") elif gender is "female": print("Welcome dear. Your room is in Block F.") else: print("Welcome sweetie. One parent should accompany you to Block A.") Here, Python goes through the second line of the code but realizes that the line is to apply only when the gender is male. However, since the participant’s gender is not male this time, Python ignores the second line of code and proceeds to the third which applies to females. It prints the output shown below. Welcome dear. Your room is in Block F. Example 7: Child Participant Now, let us see what Python will print if the participant is a child.

gender = "child" if gender is "male": print("Hi. Welcome to our weekend picnic. Your room is in Block H.") elif gender is "female": print("Welcome dear. Your room is in Block F.") else: print("Welcome sweetie. One parent should accompany you to Block A.") Notice that the fourth line of coding does not apply specifically to child. Consequently, Python will print this message once the participant does not choose male or female as their gender. As the organizer of the event, you must therefore, provide only three options – male, female or child – so that once anyone does not choose male or female, the person naturally chooses child. The output is shown below. Welcome sweetie. One parent should accompany you to Block A. The problem with this arrangement is that there may be a few mistakes resulting from any entries that fall outside the three above. For instance, someone may enter other instead of any of the three. Enter the code below and let us see what Python does. gender = “other" if gender is "male": print("Hi. Welcome to our weekend picnic. Your room is in Block H.")

elif gender is "female": print("Welcome dear. Your room is in Block F.") else: print("Welcome sweetie. One parent should accompany you to Block A.") The output is still the same as the one for a child, although this person may not necessarily be a child. Welcome sweetie. One parent should accompany you to Block A. To solve this problem and be more specific, we can still use elif in the fourth line of code and specify child. Study the code below. gender = "child" if gender is "male": print("Hi. Welcome to our weekend picnic. Your room is in Block H.") elif gender is "female": print("Welcome dear. Your room is in Block F.") elif gender is "child": print("Welcome sweetie. One parent should accompany you to Block A.") Following this code, Python will only recognize the three coded categories – male, female and child. Example 8: You can Only Choose Male, Female or Child

Now, suppose that although only the above three categories are coded, a participant still enters something other than the three. Let us assume the participant enters “other.” The code will look like what is shown below. gender = "other" if gender is "male": print("Hi. Welcome to our weekend picnic. Your room is in Block H.") elif gender is "female": print("Welcome dear. Your room is in Block F.") elif gender is "child": print("Welcome sweetie. One parent should accompany you to Block A.") However, in the output, Python prints nothing. This is because the code instructs it to print only when the response tallies with the three options but does not tell Python what to do when the code does not tally. So, instead of leaving the screen blank which may confuse the participant, we will ask Python to print a particular message. This time, we will now add else to the code. gender = "other" if gender is "male": print("Hi. Welcome to our weekend picnic. Your room is in Block H.") elif gender is "female": print("Welcome dear. Your room is in Block F.")

elif gender is "child": print("Welcome sweetie. One parent should accompany you to Block A.") else: print("Sorry! You can only choose 'male', 'female', or 'child.'") print("Please, try again.") What this code has instructed Python to do is to print the last two sentences to anyone whose entry is not male, female or child. If we now run the code, we get the output below. Sorry! You can only choose ‘male’, ‘female’, or ‘child.’ Please, try again.

Chapter Summary In this chapter, you have learned about the conditional statements. These statements enable you to give conditions which must be met for Python to execute the accompanying commands. They include if, else and elif. Diligently practice what you have learned using the exercises that follow. Exercises 1. Design a traffic control system that moderates the kind of vehicles that are allowed to use a particular lane. Prepare a list of the vehicles allowed to use the lane, and, using the if statement, instruct

Python to print a message that permits them to use the lane when they approach the traffic control. 2. Still on the traffic control system above, there are other kinds of vehicles that are not allowed to use this particular lane. Using the != and if statement, print a message that forbids them from using the lane as they approach. 3. You want to build an online game in which a person has only three shots before the game is up. Using the if and elif statements, write a program that tells the player how many shots he has left after each shot is fired. 4. In the game above, you want to disqualify any player that fires another shot even after being told at the end of his third shot that he has no more shots to fire. Using the if and elif statements, write a program for this. 5. Perhaps, you want to be more lenient to your players and decide to give them one last warning at their fourth shot before disqualifying them if they fire any other shots. Using the if-elif-else statements, write a program for this with the final warning after the fourth shot and a notice of disqualification following any other number of shots after the fourth.

CHAPTER TEN

OPERATIONS INVOLVING DICTIONARIES If you are new to programming, you have probably not heard of any other type of dictionary except the kind that contains words and their meanings. Although a dictionary in Python is not the same, it can, in fact, be made to function in a similar manner. In Python, a dictionary is a collection of well-arranged pieces of information. You may create a dictionary in order to collate and store in one place all the information relating to a particular person or subject. There is no limit to how much information you can hold in a dictionary. In this chapter, you are going to learn how to create a dictionary, how to access the information in a dictionary, how to modify the information stored in a dictionary, and much more. Example 1: Building a Basic Dictionary Let us assume that you are on the technical staff of the immigration service in your country, and the agency wants to build a dictionary containing the details of immigrants into the country. Such dictionary will contain the person’s age, gender, nationality, religion, occupation, and so on. In this example, we will create the dictionary of one of such immigrants who is 35 years, male, German, Christian, and teacher. Consider the code below. immigrant_1 = {"age": "35", "gender": "Male", "nationality": "German", "religion": "Christian", "occupation": "Teacher"} print(immigrant_1["gender"]) print(immigrant_1["nationality"]) print(immigrant_1["occupation"])

Notice that the dictionary is similar to a list except that it is not enclosed in square brackets. The pair of information in the dictionary comprises of a key which is on the left, and a value which is on the right. Each key-value pair is separated from the next by a comma. You can include many more details in the above dictionary as you want. After creating the dictionary, we asked Python to print some of the information contained in the dictionary. In requesting Python to print a piece of information from the dictionary, we only need to specify the key. Therefore, your choice of key should be easy to remember and should relate to the value desired as close as possible. The output is shown below. Male German Teacher Now, the real advantage of the dictionary will be appreciated when you are dealing with large volumes of information. For instance, it is may seem easier to go through the dictionary above with your eyes and pick out the immigrant’s information yourself. However, when you have to work with thousands of immigrants, it will be a pretty tough task. You will have to scroll down to identify the immigrant’s serial number, say, immigrant_6059, trace the dictionary horizontally and select the information you want from the key-value pairs. You can achieve this more easily if you simply specify which immigrant you want and what pieces of information you want Python to print. Python will do the background check for you and simply give you the desired output. Apart from being easier on you, it is also more accurate. To

illustrate this, we will increase the number of dictionaries to five in the example below. Example 2: A Little ‘Larger’ Dictionary In this example, we are going to create dictionaries for four more immigrants and then ask Python to print a specific piece of information, say, nationality, from all five immigrants. Study the code below. immigrant_1 = {"age": "35", "gender": "Male", "nationality": "German", "religion": "Christian"} immigrant_2 = {"age": "40", "gender": "Female", "nationality": "Indian", "religion": "Budhist"} immigrant_3 = {"age": "43", "gender": "Male", "nationality": "American", "religion": "Christian"} immigrant_4 = {"age": "54", "Sudanese", "religion": "Moslem"}

"gender":

"Female",

"nationality":

immigrant_5 = {"age": "60", "gender": "Female", "nationality": "United Kingdom", "religion": "Other"} print(immigrant_1["nationality"]) print(immigrant_2["nationality"]) print(immigrant_3["nationality"]) print(immigrant_4["nationality"]) print(immigrant_5["nationality"]) Python returns the output below. German Indian

American Sudanese United Kingdom Now, suppose that your immigration agency wishes to collect this information from the immigrants in order to determine the names of the countries from which the immigrants come. After asking Python to print the nationality of all the immigrants, you can easily see the countries that are represented. Another way to apply this is to print the occupation of each immigrant. This data will help your country to know whether the immigrants coming into the country are skilled persons or not. This will enable the country to decide how best to integrate them. You may also include in the dictionary the major reason for each immigrant’s decision to come into your country. The moment you desire to see the reasons, you simply ask Python to print the reason for you, and it will print all the reasons given by the immigrants. Example 3: Composing Messages with the Information in a Dictionary After you have built dictionaries, you may want to extract a particular piece of information and use it in a message or sentence. Python helps you do this job. You only have to compose your message and specify the key of the value you intend to include in the message. Using our dictionary above, let us compose a sentence about the first immigrant. immigrant_1 = {"age": "35", "gender": "Male", "nationality": "German", "religion": "Christian"} immigrant_2 = {"age": "40", "gender": "Female", "nationality": "Indian", "religion": "Budhist"}

immigrant_3 = {"age": "43", "gender": "Male", "nationality": "American", "religion": "Christian"} immigrant_4 = {"age": "54", "Sudanese", "religion": "Moslem"}

"gender":

"Female",

"nationality":

immigrant_5 = {"age": "60", "gender": "Female", "nationality": "United Kingdom", "religion": "Other"} nationality_1 = immigrant_1["nationality"] religion_1 = immigrant_1["religion"] print("The first immigrant is a " + nationality_1 + " " + religion_1 + ".") I have deliberately retained all the five dictionaries to enable you appreciate the difficulty involved in getting this information if you were to search for it with your eyes. Note that I began by defining a new variable, nationality_1, which is the nationality of the first immigrant. This is just to simplify the final code that I have to write. You can achieve the same result by simply entering the position of the key (immigrant_1[“nationality”]) directly into the sentence. I also defined a new variable, religion_1, for the same reason. Next, I composed a simple sentence using the variables defined above. Now, look what Python prints in the output. The first immigrant is a German Christian. Now, we will go a step further, and compose a message comparing the nationality of one immigrant with that of the other. We will now write the code below. immigrant_1 = {"age": "35", "gender": "Male", "nationality": "German", "religion": "Christian"}

immigrant_2 = {"age": "40", "gender": "Female", "nationality": "Indian", "religion": "Budhist"} immigrant_3 = {"age": "43", "gender": "Male", "nationality": "American", "religion": "Christian"} immigrant_4

=

{"age":

"54",

"gender":

"Female",

"nationality":

"Sudanese", "religion": "Moslem"} immigrant_5 = {"age": "60", "gender": "Female", "nationality": "United Kingdom", "religion": "Other"} nationality_1 = immigrant_1["nationality"] nationality_5 = immigrant_5["nationality"] print("The first immigrant is a " + nationality_1 + ", while the fifth one is from the " + nationality_5 + ".") The output is shown below. The first immigrant is a German, while the fifth one is from the United Kingdom. Example 4: Adding New Entries into a Dictionary When you start to build your dictionary, you may not have all the information you need about the particular subject or person. As more information is received, you may want to update your dictionary. Python makes room for this too. In fact, you may actually begin with an empty dictionary, and subsequently input the information into it as you get it. In this example, we will add the reason for immigration to the immigrant’s dictionary. This time, though, let us use only one dictionary to demonstrate. immigrant_1 = {"age": "35", "gender": "Male", "nationality": "German", "religion": "Christian"}

print(immigrant_1) immigrant_1["reason"] = "Political" print(immigrant_1) Notice that in the code above, we first produced the dictionary for the first immigrant, immigrant_1. Next, we asked Python to print that dictionary so that we can compare when we add new key-value pairs to it. Then, we asked Python to add a new key, “reason”, to the dictionary, and attach the value, “Political” to it. Finally, we ask Python to print it. Now compare the two dictionaries as shown in the output below. {‘age’: ‘35’, ‘gender’: ‘Male’, ‘nationality’: ‘German’, ‘religion’: ‘Christian’} {‘age’: ‘35’, ‘gender’: ‘Male’, ‘nationality’: ‘German’, ‘religion’: ‘Christian’, ‘reason’: ‘Political’} Example 5: Building a Dictionary from the Scratch Now, just as I said earlier, you can define a dictionary and leave it empty if you do not yet have what you want to put into it. As you get more information, you can then build your dictionary from the scratch. In this example, we are going to build three empty dictionaries of elementary school pupils and the scores they got in each subject at the end of an examination. Study the code below. student_1 = {} student_2 = {} student_3 = {} student_1['English Language'] = 60 student_2 ['English Language'] = 54

student_3 ['English Language'] = 68 print(student_1) print(student_2) print(student_3) Notice that we first built three empty dictionaries for the students, named student_1, student_2, and student_3 respectively. Next, we asked Python to add the key, English Language to each dictionary. We do this separately, while at the same time specifying each student’s score which is the value. Finally, we ask Python to print all the three dictionaries. Look what Python has printed in the output below. {‘English Language’: 60} {‘English Language’: 54} {‘English Language’: 68} Now, suppose you also want to add the teacher’s comment on the scores to each of the student’s dictionaries. Let us do so using the code below. student_1 = {} student_2 = {} student_3 = {} student_1['English Language'] = 60 student_2 ['English Language'] = 54 student_3 ['English Language'] = 68 student_1['Comment'] = 'Good!' student_2['Comment'] = 'Pass'

student_3['Comment'] = 'Very good!' print(student_1) print(student_2) print(student_3) In the code above, we simply defined a new key, Comment, and the corresponding value good, pass or very good for each student. Then we asked Python to print the new dictionaries. Now, look at the output Python has produced. {‘English Language’: 60, ‘Comment’: ‘Good!’} {‘English Language’: 54, ‘Comment’: ‘Pass’} {‘English Language’: 68, ‘Comment’: ‘Very good!’} Example 6: Changing the Value of a Key in a Dictionary In the last example, we built a dictionary for three pupils from the scratch containing their scores in English Language. Next, we added the teacher’s comment on each of the scores. Now, suppose that you are the teacher, and after a careful observation, you realize that the score recorded for the third student is wrong. You want to correct the score and your comment on it appropriately. You can do that by following the steps below. student_3 = {"English Language": 68, "Comment": "Very good!"} print(student_3) student_3["English Language"] = 70 student_3["Comment"] = "Excellent" print(student_3)

First, we created the dictionary of the third student containing the student’s current score and comment regarding English Language. Next, we asked Python to print the dictionary to enable us compare later. Then we defined the new score for the same subject, and a new value for the same key (comment). Finally, we asked Python to print. Look at the output below. {‘English Language’: 68, ‘Comment’: ‘Very good!’} {‘English Language’: 70, ‘Comment’: ‘Excellent’} Example 7: Removing a Key-Value Pair from a Dictionary In some situations, you may want to remove certain pieces of information from a dictionary after you have created it. Now, refer to our example above that dealt with immigrants. Suppose that a group of activists got information that the immigration agency is profiling the immigrants along religious lines and staged a public protest against it. As a result, the agency has requested you to delete religion from the dictionary of all the immigrants. You can do that following the steps below. immigrant_1 = {"age": "35", "gender": "Male", "nationality": "German", "religion": "Christian"} immigrant_2 = {"age": "40", "gender": "Female", "nationality": "Indian", "religion": "Budhist"} immigrant_3 = {"age": "43", "gender": "Male", "nationality": "American", "religion": "Christian"} immigrant_4 = {"age": "54", "Sudanese", "religion": "Moslem"}

"gender":

"Female",

"nationality":

immigrant_5 = {"age": "60", "gender": "Female", "nationality": "United Kingdom", "religion": "Other"}

print(immigrant_1) del immigrant_1["religion"] print(immigrant_1)

print(immigrant_2) del immigrant_2["religion"] print(immigrant_2)

print(immigrant_3) del immigrant_3["religion"] print(immigrant_3)

print(immigrant_4) del immigrant_4["religion"] print(immigrant_4)

print(immigrant_5) del immigrant_5["religion"] print(immigrant_5) In writing the program above, we first reproduced the original dictionaries containing the religion of the immigrants. Next, we began attending to each immigrant’s dictionary individually. This is just to enable us to compare the original dictionary with the final one. We asked Python to print the original

dictionary. After that, using del, we specified which key (religion) to be deleted from the immigrant. Finally, we asked Python to print the new dictionary. These steps are applied to all the dictionaries. Look at the output produced by Python as shown below. {‘age’: ‘35’, ‘gender’: ‘Male’, ‘nationality’: ‘German’, ‘religion’: ‘Christian’} {‘age’: ‘35’, ‘gender’: ‘Male’, ‘nationality’: ‘German’} {‘age’: ‘40’, ‘gender’: ‘Female’, ‘nationality’: ‘Indian’, ‘religion’: ‘Budhist’} {‘age’: ‘40’, ‘gender’: ‘Female’, ‘nationality’: ‘Indian’} {‘age’: ‘43’, ‘gender’: ‘Male’, ‘nationality’: ‘American’, ‘religion’: ‘Christian’} {‘age’: ‘43’, ‘gender’: ‘Male’, ‘nationality’: ‘American’} {‘age’: ‘54’, ‘gender’: ‘Female’, ‘nationality’: ‘Sudanese’, ‘religion’: ‘Moslem’} {‘age’: ‘54’, ‘gender’: ‘Female’, ‘nationality’: ‘Sudanese’} {‘age’: ‘60’, ‘gender’: ‘Female’, ‘nationality’: ‘United Kingdom’, ‘religion’: ‘Other’} {‘age’: ‘60’, ‘gender’: ‘Female’, ‘nationality’: ‘United Kingdom’, ‘religion’: ‘Other’}

Example 8: Building a Dictionary for only One Kind of Information In the previous examples, what we have been doing is building a separate dictionary for each person. However, we can still build one dictionary that

stores information about different people. Suppose that you are an air transport official and your company has asked customers to give feedback on their experiences flying with your company. Now, you are to prepare a dictionary for feedback and include each customer’s first name and the comment. You can do that by following the steps below. feedback = {"Bill": "Fantastic", "Ciara": "Boring", "Fred": "Indifferent", "Mills": "Fair",} print(feedback) Python prints the dictionary as shown in the output below. {‘Bill’: ‘Fantastic’, ‘Ciara’: ‘Boring’, ‘Fred’: ‘Indifferent’, ‘Mills’: ‘Fair’} Example 9: Using the For Loop in a Dictionary In our examples so far, we have been asking Python to print only certain parts of the dictionary. Supposing we wanted to print everything held in a particular dictionary, issuing a command for each key would be too cumbersome. This is where the for loop comes handy. In this example we are going to use the for loop to print all the information in a dictionary. Our dictionary is a collection of students’ first names and their scores in English Language examinations. We will loop through it using the steps below. english_language = { 'Fred': '60', 'Annie': '56', 'Andie': '50', 'Ann': '45', 'Clement': '65'

} for student, score in english_language.items(): print("\nStudent: " + student) print("Score: " + score) In the program above, we first created a dictionary of the students’ scores in English Language. Notice that this time, our key-value pairs are arranged vertically, one pair on each line. Next, we use the for loop to ask Python to go through the entire dictionary. This line of code (for student, score in english_language.items():) should be read as, “for every student with a score in the english_language dictionary, as items . . .” Notice the ellipses at the end of the sentence above. These are to show that the sentence continues with the lines of code under it. That is why the full colon (:) is present at the end of the for loop statement. The .items() method lets Python know that it is to treat the content of the dictionary as items. The sentence above continues to the next two lines. The first line ask Python to print an arbitrary text, “Student: ” and concatenate it to what Python stored in student. The first “Student” and the second one do not have to match. The first is an arbitrary text you have chosen to be displayed where the student’s name (student) will be entered. The same principle applies to the second line. Python prints the output below. Student: Fred Score: 60 Student: Annie Score: 56 Student: Andie

Score: 50 Student: Ann Score: 45 Student: Clement Score: 65 Example 10: Making the For Loop Work with only Keys You know by now that a dictionary contains a key word and its associated value. In the above example, you have learned how to loop through the entire dictionary, that is, the keys and their values. However, sometimes situations arise which may require you to loop through only the keys in a dictionary. In this example, we are going to do just that. Now, suppose that in the example above, a certain student in the class, named Johnson, has lodged a complaint at the Students’ Affairs Division, claiming that he sat the exam but has not seen his scores. You have been asked by the Students’ Affairs Division to check whether he actually took the exam or not. Notice that in this situation, you are not yet bothered about scores, so you just want to display the list of students who took the exam. You can use the for loop to go through the dictionary and print out the names of students who sat for the exam. Look how we do it below. english_language = { 'Fred': '60', 'Annie': '56', 'Andie': '50',

'Ann': '45', 'Clement': '65' } print("These are the names of students who sat for the exam:") for student in english_language.keys(): print(student.title()) In this example, we first produced the dictionary containing the names and scores of the students who sat for the examination in English Language. Next, we asked Python to print a preamble to the list we intend to display. After this, we use the for loop to ask Python to print in the title case every student found in that dictionary. Python processes this command in a stepwise fashion. First, it loops through the entire dictionary and collects the names of the students one name per time. Python stores these collected names in a defined location called student. Finally, it prints every name collected in students using the title case. This produces the output below. These are the names of students who sat for the exam: Fred Annie Andie Ann Clement Example 11:

In the example above, you can see by physical inspection that the student who complained, Johnson, did not sit the exam because his name is not among the names of those who sat the exam. However, supposing you had to look for Johnson’s name in a list of one thousand students, you would find it rather hectic. Here too, Python comes to the rescue. We can make Python print a message depending on the outcome of the search. If Johnson’s name is found among those who took the exam, we can ask Python to print an apology for him containing his score in the exam. But if not, we can ask Python to leave Johnson a message asking him to prepare to take the exams another time. However, suppose that one of the students who actually sat the exam, Andie, is also complaining, and we decide to check his name in the dictionary. Just like in Johnson’s case, if we find his name, we will apologize to him and print the scores. On the contrary, we will advise him to take the exam another time. We can now write the program as shown below.

english_language = { 'Fred': '60', 'Annie': '56', 'Andie': '50', 'Ann': '45', 'Clement': '65' }

complainants = ['Johnson', 'Andie']

for student in english_language.keys(): print(student.title())

if student in complainants: print('Dear ' + student.title() + ', ' + 'we are sorry for not displaying your result earlier' + '.' + 'Your score is' + ' ' + english_language[student] + '.')

if complainants != english_language: print ('Sorry ' + complainants[0].title() + ', ' + 'you did not sit for the exam. Therefore, you have no score.') As usual, we began by reproducing the dictionary of all the students who sat the English Language exam and their respective scores. Next, we produced a list of the two students whose complaints have been received who are Johnson and Andie. Thereafter, we asked Python to print in title case the name of each student found in the dictionary. Using the if statement, we asked Python to print the message of apology to each student whose name is in the dictionary and also in the list of complainants. This message is also to contain the student’s score which is to be simultaneously fetched from the dictionary. Finally, still using the if statement, we ask Python to print a message to those students who are among the complainants but whose names are not

found in the dictionary. Python produces the output shown below. Fred Annie Andie Dear Andie, we are sorry for not displaying your result earlier. Your score is 50. Ann Clement Sorry Johnson, you did not sit for the exam. Therefore, you have no score. Now, if you look at the output above, you will notice that Python has even mentioned the names of students who have nothing to do with either of these conditions. This is because using the for loop, we asked Python to print the name of every student found in the dictionary. The meaning of the for loop is that Python will go through that dictionary as many times as necessary to attend to each student individually. Each time Python finds a student in the dictionary, it prints the name. That is how it printed Fred, Annie, and Andie. However, because another command exists under the for loop that asks Python to print a customized message to a student if in addition to be found in the dictionary, he is also found in the list of complainants, as Python picks a student in the dictionary, it prints the name. Then it returns to the list of complainants. If it finds the student’s name there, it prints the customized message. That is why when Python gets to Andie, it prints his name, and prints the customized name, displaying Andie’s score.

The next line of the program begins with another if statement. This time, Python is to print a different message to any student found among the complainants but who is not (!=) found in the dictionary of those who sat for the exams. Notice here that the if statement begins on its own line and has no indentation. This means it is not related to the for loop above. In other words, this action will not be performed for every student in the dictionary. Now, to remove the names of those unaffected students from the output, we will remove the print command immediately under the for loop. The program will now look as shown below. english_language = { 'Fred': '60', 'Annie': '56', 'Andie': '50', 'Ann': '45', 'Clement': '65' }

complainants = ['Johnson', 'Andie'] for student in english_language.keys(): if student in complainants: print('Dear ' + student.title() + ', ' + 'we are sorry for not displaying your result earlier' + '.' + 'Your score is' + ' ' + english_language[student] + '.')

if complainants != english_language: print ('Sorry ' + complainants[0].title() + ', ' + 'you did not sit for the exam. Therefore, you have no score.') Now look at the simple output that Python produces as shown below. Dear Andie, we are sorry for not displaying your result earlier. Your score is 50. Sorry Johnson, you did not sit for the exam. Therefore, you have no score. Example 12: Printing Only the Values in a Dictionary In the examples above, you have learned that you can loop through a dictionary and ask Python to print only the keys in the dictionary. We have seen the areas in which this can be practically applied in real-life situations. In the same vein, sometimes you may want to deal only with the values in a dictionary. In this case, you will use the values() method. In this example, let us use the dictionary in the last example. Suppose that the teacher in that class decides to take a look at the general performance of the students without bothering about which student scored which points. He/she can use the program below to achieve that. english_language = { 'Fred': '60', 'Annie': '56', 'Andie': '50', 'Ann': '45', 'Clement': '65'

} print('These are the scores made by the students:') for score in english_language.values(): print(score) Python goes through the dictionary and picks out the scores. Look at the output below. These are the scores made by the students: 60 56 50 45 65

Chapter Summary In this chapter, you have learned about dictionaries in Python. You have learned that dictionaries are a collection of related items held together in braces. Dictionaries differ from lists only by the braces and the fact that the content of dictionaries are arranged in two-word pairs in which the first is referred to as the key and the second is referred to as the value. The value is the entry that represents what the key stands for. You have also learned a couple of methods for manipulating dictionaries in Python, and what reallife situations these operations may be needed. Now, practice with the exercises given below.

Exercises 1. The prison service in your country is worried about its reputation for poor record-keeping. Its inability to keep proper records has caused a lot of injustice to some of its inmates who end up spending more time in jail than is necessary because no one remembers when their jail term expires. As part of its upgrade, it has hired you to help with organizing the data of the inmates. Now, with your knowledge of Python, create a simple dictionary for one inmate with the following keys: name, age, gender, crime, due for release, and option of fine. 2. Now, while working on the same project, create the dictionary above for one more inmate. This time, print simple messages about their stay in the jail, stating their crimes and dates of release. 3. A human rights group has sued the prison service on account of three of the prisoners (Murray, Tim and Frank) whom it claims have over-stayed their jail sentence. First, create two lists of prisoners, one for all those due for release, and the other for those already released. Using everything you have learned so far in Python, search the two lists. If you find any prisoner due for release but who has not been released yet, print a message of apology to them, stating that they will be released immediately. However, if their sentences have not expired, print a different message to them, telling them their term is still running, and wishing them good luck the next time they check. 4. In the same legal battle, the human rights group is claiming that three prisoners (Tim, Fog, and Murray) are in one of the country’s jails. Perform a search for these chaps, and if they are in jail, print a

confirmation message, detailing their due for release status. Otherwise, print a message denying that they are in jail.

CHAPTER ELEVEN

NESTING DICTIONARIES AND LISTS In the previous chapter, you learned to perform operations using dictionaries. As you work on bigger projects, you will be working with huge dictionaries. For the sake of simplicity and the economy of space, you will want to organize them in a manner that allows groups of dictionaries to be held in one dictionary or one list, or groups of lists to be held in one dictionary. This is called nesting in Python. Example 1: Nesting Dictionaries in a List One of the schools in your district has decided to conduct a poll among its students regarding which subjects are their favorite and which ones are their worst. As a Python guru in the district, you have been invited to process this information. Create dictionaries for five of the students containing their responses to this poll. Next, create a list which contains all these dictionaries. You can do that by writing the program below. student_1 = {'favorite': 'Mathematics', 'worst': 'English'} student_2 = {'favorite': 'Arts', 'worst': 'Mathematics'} student_3 = {'favorite': 'Religion', 'worst': 'Mathematics'} student_4 = {'favorite': 'English', 'worst': 'Arts'} student_5 = {'favorite': 'Agriculture', 'worst': 'Religion'}

students = [student_1, student_2, student_3, student_4, student_5] for student in students: print(student)

First, we created individual dictionaries for five students. Next, we created a list and lumped the five dictionaries into it. Finally, we asked Python, using the for loop, to print any dictionary found in the list. Python executes this command in multiple steps. Each time it loops through the list and finds a dictionary, it stops there and goes to print it. Next, it returns to loop through the list one more time until it has printed all the dictionaries. See the output produced by Python below. {'favorite': 'Mathematics', 'worst': 'English'} {'favorite': 'Arts', 'worst': 'Mathematics'} {'favorite': 'Religion', 'worst': 'Mathematics'} {'favorite': 'English', 'worst': 'Arts'} {'favorite': 'Agriculture', 'worst': 'Religion'} Example 2: Working with a Larger Number of Dictionaries The example above dealt with only five students. However, what if you were dealing with a larger number of dictionaries, say, one hundred? This can be the case where you want to create a computer game using puppies. Each puppy is described by an individual dictionary comprising of its color and speed. If you decide to build these dictionaries manually, it will take you a lot of time. However, you can use Python to build them, and then modify them as you choose. That is what we will demonstrate in this example. #Creating a mother list to house the puppies. puppies = []

#Making 100 new puppies.

for total_puppies in range(100): new_puppy = {'color': 'grey', 'speed': '10'} puppies.append(new_puppy)

#Let us show the first 5 puppies. for puppy in puppies[:5]: print(puppy) print('. . .')

#Let us now show the total number of puppies created. print('The complete number of puppies is ' + str(len(puppies))) Notice that due to the relative complexity of the program above, we have begun using comments which we introduced much earlier in the book. Comments are preceded by the hash (#) sign and are not codes, hence will not be printed in the output. In terms of the actual code, we began by creating an empty list of puppies. Using the range() function, we chose to make 100 puppies. To describe the content of each of these puppy dictionaries, we used the for loop. This instructs Python that for a total of 100 puppies, each new puppy dictionary should contain a grey colored puppy with a speed of 10. Using the append() method, we added the new puppy just described. Since it is the for loop, Python will append this new puppy to that list one at a time for 100 times. Next, we chose the number of puppies to print. Again, using the for loop, we instructed Python to print every puppy found in the list of puppies up to

the fifth puppy. Now to show there are more puppies not being displayed, we also asked Python to print ellipses (. . .) at the end of the dictionaries of puppies. Finally, we made a statement, giving the total number of puppies. Look what Python has produced in the output as shown below. {'color': 'grey', 'speed': '10'} {'color': 'grey', 'speed': '10'} {'color': 'grey', 'speed': '10'} {'color': 'grey', 'speed': '10'} {'color': 'grey', 'speed': '10'} ... The complete number of puppies is 100 Example 3: Modifying the Dictionaries in a List In the above example, the puppies produced by Python all have the same color and speed. Now, suppose that you want to change the color and speed of two of them. In that case, we will use the program below. #Creating a mother list to house the puppies. puppies = []

#Making 100 new puppies. for total_puppies in range(100): new_puppy = {'color': 'grey', 'speed': '10'} puppies.append(new_puppy)

for puppy in puppies[0:2]: if puppy['color'] == 'grey': puppy['color'] = 'black' puppy['speed'] = 12

#Let us show the first 5 puppies. for puppy in puppies[:5]: print(puppy) print('. . .')

#Let us now show the total number of puppies created. print('The complete number of puppies is ' + str(len(puppies))) We began by creating 100 puppies as described in the previous example. Next, using the for loop, we instructed Python concerning any puppy found among the first two puppies. We used the if statement to further give a condition that must be met by these first two puppies for Python to carry out the last command in this paragraph of code. The instruction is that if the color of the first two puppies is grey, Python should change the color to black, and the speed to 12. The rest of the code is the same with what is obtainable in the previous example. Now, see what Python produces in the output as shown below. {'color': 'black', 'speed': '12'} {'color': 'black', 'speed': '12'} {'color': 'grey', 'speed': '10'}

{'color': 'grey', 'speed': '10'} {'color': 'grey', 'speed': '10'} ... The complete number of puppies is 100 Notice that the first two puppies are now black in color and have the speed of 12. Chapter Summary In this chapter, you have learned about what is called nesting in Python. This involves putting dictionaries into lists and putting lists into dictionaries. You have learned how to access the individual dictionaries that are nested in a list. Practice with the exercise below. Exercise Think of at least two real-life situations in which you may need to nest a dictionary in a list. Now, create five dictionaries in each situation, nest them in a list, and compose some messages with the content of the lists.

CHAPTER TWELVE

OPERATIONS INVOLVING USER INPUT AND WHILE LOOPS Most real-life programs are written in order to interact with the user, receive a form of information from them and process such information according to laid down codes. So far in our programming journey, we have not given such leverage to the user. We have however provided room for some form of input, but not at the interphase when the program interacts directly with the user and allows the user to determine the direction of flow. The input() function enables Python to pause while executing a program until it receives input from the user. The program can be written in a manner that the next line of interaction is dependent on the user’s input and therefore determined by the user.

Example 1 In this example, we are going to write a program that asks the user for their name and then prints a welcome message with the user’s name in it. We will use the code below. message = input("Please enter your name: ") print("Dear " + message + "," + "we are glad to have you.") In the code above, the variable, message, is defined as the input the user will enter when prompted. It is not the statement included in the parentheses following input. Now, run this program and consider the output. The

program runs in two steps. The first step prompts you for an input and waits for you as shown below. Please enter your name: If you enter “James,” as your name and hit the Enter key, the program runs through the last step and Python returns the message below. Please enter your name: James Dear James, we are glad to have you. The instruction you pass to the user regarding what information to enter is called a prompt. To avoid ambiguity, make your prompts clear, simple and short. Example 2 You are employed by a regulatory agency in the automobile industry to write a program that will run in simple mobile application which the agency intends to use to screen tires and state whether they are expired or not. The underlying guideline is that any tire which has been in use for more than 3 months is expired. Let us write the program as shown below. message = input("Age of tyre (months): ") message = int(message) if message >= 3: print("Your tyre is expired. Try and replace it.") First, we created a variable called message, which contains the input after a user enters the age of his tyre in months. Next, we converted the input to an integer using the int() function. This is necessary to enable us use the if statement and compare the user’s input with the number 3 which is the cutoff mark. Without this conversion, the user’s entry will be treated by Python

as a string value and therefore, Python will not be able to compare the two since they will be of different types of values. Finally, we ask tell Python what to print if the user’s input is greater than or equal to 3. Again, the program will run in two steps and give the following output for a number greater than 3. Age of tyre (months): 4 Your tyre is expired. Try and replace it.

Example 3 In the example above, there is a message for Python to print when the tyre is expired. However, when the tyre is not expired, Python says nothing. This is because we have not instructed Python on what to do when a tyre is not expired. So, in this example, we are going to use the else statement to tell Python to print a message for those whose tires have not expired. message = input("Age of tyre(months): ") message = int(message) if message >= 3: print("Your tyre is expired. Try and replace it.") else: print("Congratulations! Your tyre has not expired. \nPlease, note that it expires after 3 months of use.")

Python gives the output below. Age of tyre (months): 2

Congratulations! Your tyre has not expired. Please, note that it expires after 3 months of use. Did you notice the \n in front of the second sentence? It is the code for starting off on a new line. The Concept of While Loops In most games, the system prompts the user to make a certain input, and a certain output is then generated. However, to make the games fun, there must be a level of continuity in the flow. The while loop enables Python to keep running a particular routine as long as a certain condition is met. Example 4 In this example, we are going to write a program for a simple game. This game is built to “throw back” at the user whatever object the user throws at the game. So, if the user throws a stone at the game, the game throws a stone back at the user. Consider the program below. prompt = "\nThrow anything to me, and I throw it back to you:" prompt += "\nEnter 'quit' to end the program. " message = "" while message != 'quit': message = input(prompt) if message != 'quit': print(message) To begin with, we defined a variable called prompt, which is what Python will display to the user to inform the user of how to interact with the game. The second line notifies the user that he can quit the game by entering the

word quit. The while loop was used to ask Python to continue throwing back to the user whatever the user entered as long as it was not the word quit. Now, run the program and see what output Python produces. Throw anything to me, and I throw it back to you: Enter ‘quit’ to end the program.

Chapter Summary In this chapter, you have learned the input and while functions, and how to use them in Python. You have seen how the input function allows Python to pause while executing a program in order to receive input from the user. You have also seen that with the while function, you can make Python continue to execute a repeated sequence of action while receiving input from the user. You may now practice what you have learned using the exercises below. Exercises 1. You are hired by a client in the hospitality industry to write a program that welcomes a guest to the hotel when they check into their rooms. The client wants you to make Python welcome these guests by their names. Using the input function, write a program that asks them for their names and then types a message for them when they enter their names. 2. You are the students’ affairs officer of your institution, and the management of the institution has noticed that students are deceiving their parents and extorting money from them in the guise of purchasing some items from the school. You have decided to design an app that enables parents to secretly verify whether the

school actually sells an item or gives it to students for free. Write the code for this app. 3. You are hired by the drugs regulatory agency in your country to design them an app that enables the general public to verify the actual expiry status of each medicine they buy. This has become necessary because dishonest medicine sellers have been erasing and extending the expiry date on the medicines in their store each time they expire. The drugs are to henceforth come labelled with unique codes which only get interpreted when tested in this app. Write a program in Python that asks users for the number on their medicines, cross-checks with the system, and returns a message about the status of the medicine.

CHAPTER THIRTEEN

OPERATIONS USING DEFINED FUNCTIONS In our journey so far in learning to write programs in Python, each time we want to perform a task, we must write the particular code for the task to enable Python to execute it. This is exciting too but can get tiring when we are working with huge volumes of data when the code is rather bulky. Using functions, we can develop a simpler way of performing the same tasks. A function is a body of codes which defines exactly what kind of operation Python should carry out. After defining a function, you can make Python perform that operation by simply calling the function or referring Python to it.

Example 1 In this example, we are going to define a function that prints a simple welcome message. Study the code below. def welcome_user(): """Write a short welcome message.""" print("Welcome, buddy!") welcome_user() In the code above, we began by defining a function called welcome_user. Notice the def in front of the function which tells Python that we are defining a function there. The full colon at the end of the function tells Python that what is following is under the function. Next, we describe what the function does by enclosing it in three sets of quotation marks. This description is also called a docstring. Then, we

instruct Python what to do each time we call that function. Finally, we call the function by simply typing welcome_user(). Python produces the output below. Welcome, buddy! Example 2 In this example, we are going to define the same function as above. However, we will modify the function to enable Python type the welcome message using the person’s name. Study the code below. def welcome_user(username): """Write a short welcome message.""" print("Welcome," + username.title() + "!") welcome_user("fred") Notice that in the code above, we have included a parameter called “username” in the parentheses following the derivative. This is to tell Python that we intend to include a username in the function. Next, we ask Python to print the welcome message. This time, though, because the welcome message contains the username which is a proper noun, we use the .title() method to make Python print the first letter in a capital letter. Finally, we call the function to print that message. Notice that we have now entered a specific argument called fred, in the parentheses. Python therefore, prints the welcome message, mentioning Fred by name as shown below. Welcome, Fred!

Example 3 In this example, we are going to call the welcome_user function with three different usernames and see what Python will produce in the output. def welcome_user(username): """Write a short welcome message.""" print("Welcome," + username.title() + "!") welcome_user("fred") welcome_user("jessica") welcome_user("tom") Notice that Python prints a separate welcome message for each user by name. Welcome, Fred! Welcome, Jessica! Welcome, Tom! Example 4 In the last two examples, you have learned how to include a parameter in your function, and how to enter an argument when calling that function. However, you learned how to do this only to one parameter and one argument. Nevertheless, there may be moments when you need to include multiple parameters to enable you enter multiple arguments. You can do this in a number of ways. In this example, we will consider one of them.

def describe_institution(institution_type, institution_name): """Compose a short sentence about my institution.""" print("My institution is a " + institution_type + ".") print("The name of my " + institution_type + " is " + institution_name.title() + ".") describe_institution("school", "lincoln university") Notice in the code above that we now have two parameters: institution_type and institution_name. Next, we asked Python to print two sentences using the parameters. Finally, as we call the describe_institution function, we enter the arguments for each parameter. Now, look at the output as shown below. My institution is a school. The name of my school is Lincoln University. The style we have used in this example to define multiple parameters is called positional because Python relies on the position of the arguments we enter to know which one is for institution_type and which one is for institution_name. If we distort this arrangement, Python prints a funny output. Now consider the code below. def describe_institution(institution_type, institution_name): """Compose a short sentence about my institution.""" print("My institution is a " + institution_type + ".") print("The name of my" + institution_type + " is " + institution_name.title() + ".") describe_institution("lincoln university", "school")

Note in the code above that we have interchanged the positions of the arguments lincoln university and school. Now, see what Python prints. My institution is a lincoln university. The name of my lincoln university is School. Apart from the obvious distortion, notice that “lincoln university” is printed in lower case, while “school” is printed in title case. This is because when we interchanged the arguments, the .title() method which converts to title case now applies to “school” rather than “lincoln university.”

Example 5 In this example, we are going to write code that will help Python to be more specific irrespective of the arrangement of the arguments. Study the code below carefully. def describe_institution(institution_type, institution_name): """Compose a short sentence about my institution.""" print("My institution is a " + institution_type + ".") print("The name of my " + institution_type + " is " + institution_name.title() + ".") describe_institution(institution_name institution_type = "school")

=

"lincoln

university",

Notice that the code above is not different from the one in the last example, except for the last line. In the last line while calling the function, we

introduced key word pairs. This enables Python to know which argument is for institution_name and which argument is for institution_type. As a result, the order no longer matters. Python still produces the correct output as shown below. My institution is a school. The name of my school is Lincoln University.

Chapter Summary In this chapter you have learned how to create or build new functions which enclose a body of codes for performing a particular task. You have also learned how to add parameters when defining a function and how to enter arguments when calling that function. In addition, you have learned how to compose messages with the arguments in a function by simply calling that function. You may now practice with the exercises below.

Exercises 1. Define a simple function bye_bye, and use it to print a simple bye message. 2. Modify the function above to include a parameter, name, and enter the argument when calling the function to print the same bye message, this time, mentioning your friend’s name. 3. An elementary school in your town has hired you to build them a simple mobile app to help the pupils with reciting a poem. The poem is to accommodate in specific places, the name of the pupil, age of the pupil, the pupil’s class, the name of the pupil’s favorite teacher, and a line stating that the pupil is proud of the teacher.

Define a function, pupils_identity, with the following parameters: pupils_name, pupils_age, pupils_class, and favorite_teacher. Write the program to execute the poem below: My name is Jane I am 8 years old. I am in Class 4. My favorite teacher is Ferguson. I am proud of him. 4. Call the function in the last exercise and enter the arguments for three pupils in order to print the poem the way each pupil would recite it.

CHAPTER FOURTEEN

OPERATIONS INVOLVING CLASSES In the course of writing software, the programmer often must think beyond codes and segregated projects to take a more holistic view of life. How may he represent real-life situations using codes? How may the new software tangibly mimic real-life situations and solve real-life problems? This approach to programming is otherwise referred to as object-oriented programming. It simply means although the programmer uses codes, his bigger picture is how he can create typical objects with their features. To achieve this objective, programmers must use classes.

A class is a broad definition of the attributes of an object. When a class is drawn up, it represents features or qualities that are common to certain objects. From one class, additional qualities or features can be added to the objects in order to create distinct objects which now contain both the features general to the class and some unique features. Each time you make a unique object from a class in the manner described above, you are doing what is called instantiation, and what you are working with is called an instance of a class. Example 1: How to Create a Class What you can mimic using classes is up to your imagination. In this example, we are going to create a class called Boy. Generally, boys have names and an age. In addition, boys also run and jump about. These general pieces of information about how boys are identified and what they do, will be entered into our class, Boy. With this class, Python is going to try to

create an object that models a boy. After creating the general class, we will then proceed to use this class to create specific boys. Each of the specific boys or instances to be created from the class will have a name and an age. In addition, it will also have the ability to run and to jump. Let us write the program below. class Boy(): """This is a step towards modelling a class of boys.""" def __init__(self, name, age): """Beginning with name and age attributes.""" self.name = name self.age = age def run(self): """Modelling a boy who runs in response to a command.""" print(self.name.title() + " is now running.") def jump(self): """Modelling a boy who jumps in response to a command.""" print(self.name.title() + " is now jumping.") In the program above, we began by defining a class called Boy. You will notice that since we started writing programs in this book, we have been using small letters of the alphabet. In Python, whenever you see capital letters, the refer to a class. Since we are starting with an empty class, the brackets following Boy are empty. Next, we wrote a docstring to describe what the Boy class is set out to achieve. After this, there is the __init__()

method. Note that this method has two underscore signs in front of it and behind it. The significance of this is that Python will execute the method we are defining here whenever a new instance is created from the original class, Boy. This simply means each time we create a unique boy, Python will add to him the general attributes defined in the original class. Thereafter, we added self, name, and age as parameters to the __init__() method. The parameter named self has to come first before the others. It has to be added to the definition of the method to enable Python to automatically add the general attributes of the class to any instance (unique boy) being produced from the general class. It does this by passing the self-argument. As a result, every time we create a new instance from the original class, we only need to provide values for the name and age. The variables that begin with the prefix self such as self.name and self.age are applicable to every instance produced from the original class. We created two more methods run() and jump(). These ones only contain the parameter, self. They also will be added to every instance created subsequently from the class. What this means is that all the boys that will be created from the master class, Boy, will be able to run and jump. At this level, there may not be any real excitement yet. However, this program can be integrated into a real-time computer game which will make animated boys run and jump. Example 2: Producing Instances from a Class Another way to look at a class is to consider it a body of directives on how to make an instance. In the example above, we can consider a class as the set of instructions laid down for making any particular boy. With the

program below, we can now make an instance that represents a particular boy. class Boy(): """This is a step towards modelling a class of boys.""" def __init__(self, name, age): """Beginning with name and age attributes.""" self.name = name self.age = age def run(self): """Modelling a boy who runs in response to a command.""" print(self.name.title() + " is now running.") def jump(self): """Modelling a boy who jumps in response to a command.""" print(self.name.title() + " is now jumping.")

boy_1 = Boy('Tom', 8) print("The first boy's name is " + boy_1.name.title() + ".") print("He is " + str(boy_1.age) + " years old.") Notice that the above program is essentially the same as the one in the first example except for the last paragraph. The last paragraph is actually the one that creates an instance of the class. In other words, it is the program that creates a specific boy named Tom who is 8 years old. The first line of this paragraph requests Python to create a

new boy from the class, Boy. When we do this, Python calls the __init__() method. The moment this method is called, it creates a specific boy using the name and age provided. After this creation, Python stores the boy’s name and age in boy_1. To access it and print a statement about the specific attributes of this boy, we use the dot notation. For example, to access the boy’s name, we write boy_1.name. Python then reaches out to the instance and retrieves the value stored in the place of name in the general class. The same thing happens when we write boy_1.age to access the boy’s age. That is why when we print, the name and age of this specific boy are used. The first boy’s name is Tom. He is 8 years old. Example 3: Accessing Methods in a Class Notice that in the first example when we wrote the program for creating instances from the class, Boy, we created two methods, run() and jump(). To call these methods for this instance, boy_1, that we have created, we still use the dot notation in the same way we did in the second example. Look at the program below. class Boy(): """This is a step towards modelling a class of boys.""" def __init__(self, name, age): """Beginning with name and age attributes.""" self.name = name self.age = age def run(self): """Modelling a boy who runs in response to a command."""

print(self.name.title() + " is now running.") def jump(self): """Modelling a boy who jumps in response to a command.""" print(self.name.title() + " is now jumping.")

boy_1 = Boy('Tom', 8) boy_1.run() boy_1.jump() Again, our focus is on the last paragraph of the program. Here, you will notice that we called the two methods we defined earlier in the program. These methods are the run() and jump() methods. By writing boy_1.run() we simply instructed Python to run the program represented by the run() method using the values we defined for the first boy. The same is requested of Python when we wrote boy_1.jump(). Now, what exactly did we program in the run() method? We will find out by going to its definition in the body of the program above. You will notice that we defined it to include an instruction for Python to print a sentence beginning with the boy’s name and ending with “. . . is now running.” For the jump() method, the instruction was to print a sentence beginning with the boy’s name and ending with “. . . is now jumping.” Anywhere we call these methods, that is exactly what Python will do. Now, look at the output produced below. Tom is now running. Tom is now jumping. Example 4: Creating Multiple Instances

In the last example above, you will notice that we have been working with only one instance, the boy_1. However, there is no limit to how many instances you can create from your class. In this example, we will create a second boy whom we will call boy_2. Study the program below. class Boy(): """This is a step towards modelling a class of boys.""" def __init__(self, name, age): """Beginning with name and age attributes.""" self.name = name self.age = age def run(self): """Modelling a boy who runs in response to a command.""" print(self.name.title() + " is now running.") def jump(self): """Modelling a boy who jumps in response to a command.""" print(self.name.title() + " is now jumping.")

boy_1 = Boy('Tom', 8) boy_2 = Boy('Tony', 10)

print("The first boy's name is " + boy_1.name.title() + "." ) print(boy_1.name.title() + " is " + str(boy_1.age) + " years old.") boy_1.jump()

print("The second boy's name is " + boy_2.name.title() + ".") print(boy_2.name.title() + " is " + str(boy_2.age) + "years old.") boy_2.run() In this example, we have created a second boy called boy_2 whose name is Tony and who is 10 years old. Now, look at the output Python has produced from the program that followed. The first boy’s name is Tom. Tom is 8 years old. Tom is now jumping. The second boy’s name is Tony. Tony is 10 years old. Tony is now running.

Example 5: Students’ Scores In the previous example, we built a class of boys and defined methods which we used to execute certain in-built programs with the attributes of each of the boys. In this example, we are going to create a class of students. These are students who have taken an examination. This class is created to help organize their results and also display them. Study the program below. class Students(): """This is a step towards modelling a class of students.""" def __init__(self, name, subject, score):

"""Beginning with name, subject and score attributes.""" self.name = name self.subject = subject self.score = score def fetch_students_details(self): """Aim is to retrieve student's name, subject and score.""" full_details = self.name.title() + " scored " + str(self.score) + " in " + self.subject.title() + "." return full_details student_1 = Students('Jane', 'English Language', '57') print(student_1.fetch_students_details()) In the program above, we first created a class called Students. The docstring under it describes what the class is aimed at achieving. Next, we defined the __init__() method with three attributes in addition to self, which include name, subject and score. The __init__() method takes in these attributes and gives us the dot notation for them. For example, the notation for retrieving the name of any specific student is self.name. Self in this notation represents the general class, Students. Later on when we create an instance (always remember that an instance is just a specific member of a class) of this class, the notation will read as instance.name. The same principle applies to the attributes as well. Next, we defined a new method called fetch_students_details. We assigned this method the function of retrieving the student’s name, subject and score in that subject. Then we created a variable named full_details which is assigned a simple sentence about the student’s name, score and subject

which are in turn fetched using the self.name, self.score and self.subject notations. Finally, we made an instance from the class, Students, and called it student_1, which is a particular student whose name is Jane, and who scored 20 in English Language. Then we asked Python to print the details of the student by calling the fetch_students_details for this particular student using student_1.fetch_students_details(). Consider the output produced by Python below. Jane scored 57 in English Language. Example 6: Attributes with a Default Value In the example above, the student scored 57 in English Language. Now, suppose that as the schoolteacher, you decided to give a bonus mark of 5 points to all the students who sat for the English Language exam. Therefore, you want to rewrite the program above to set a default value for the bonus. However, since this attribute has the same value for all the students, you want to make it a default one. This will ensure that each student by default has 5 points. You can rewrite the program as shown below. class Students(): """This is a step towards modelling a class of students.""" def __init__(self, name, subject, score): """Beginning with name, subject and score attributes.""" self.name = name self.subject = subject self.score = score

self.bonus = 5 def fetch_students_details(self): """Aim is to retrieve student's name, subject and score.""" full_details = self.name.title() + " scored " + str(self.score) + " in " + self.subject.title() + "." return full_details def general_bonus(self): """This is a bonus which every student will have.""" print(self.name + " also has a bonus of " + str(self.bonus) + " points.") student_1 = Students('Jane', 'English Language', '57') print(student_1.fetch_students_details()) student_1.general_bonus() In the program above, the arrangement is essentially the same with that of the previous example except the addition of self.bonus under the __init__() method. Two paragraphs later, we defined a method for it called general_bonus, which explains that the bonus is for every student. This method also includes a command to print the name of the student with a statement which says she has bonus points. To call this method to apply to student_1, we wrote student_1.general_bonus(). The output produced by Python is shown below.

Jane scored 57 in English Language. Jane also has a bonus of 5 points.

Example 7: Directly Modifying the Value of an Attribute Supposing that in the example above, the results of the students were compiled and sent to the examination board of the faculty, and the board observed that the bonus mark assigned to the students was too high. You were therefore, asked to reduce it to 3 points. You can use the program below to modify the value directly. class Students(): """This is a step towards modelling a class of students.""" def __init__(self, name, subject, score): """Beginning with name, subject and score attributes.""" self.name = name self.subject = subject self.score = score self.bonus = 5 def fetch_students_details(self): """Aim is to retrieve student's name, subject and score.""" full_details = self.name.title() + " scored " + str(self.score) + " in " + self.subject.title() + "." return full_details def general_bonus(self): """This is a bonus which every student will have.""" print(self.name + " also has a bonus of " + str(self.bonus) + " points.")

student_1 = Students('Jane', 'English Language', '57') print(student_1.fetch_students_details()) student_1.bonus = 3 student_1.general_bonus() Notice that the only thing that has changed in this program is the addition of student_1.bonus = 3 in the second to the last line of the program. Note also that the original definition of this value in the __init__() method in the program has remained intact. Now, look what output Python has produced. Jane scored 57 in English Language. Jane also has a bonus of 3 points. Example 8: Modifying the Value of an Attribute by Using a Method Another way to modify an attribute’s value is to create a method that does it for you. From the example above, suppose that the scores recorded for the students in English Language were what they scored out of seventy points, with the remaining 30 points to be awarded after a continuous assessment subsequently. Now that the continuous assessment has been conducted and marked, you want to create a method that will update each student’s score. The program for doing this is written below. class Students(): """This is a step towards modelling a class of students.""" def __init__(self, name, subject, score): """Beginning with name, subject and score attributes.""" self.name = name self.subject = subject

self.score = score self.bonus = 5 def fetch_students_details(self): """Aim is to retrieve student's name, subject and score.""" full_details = self.name.title() + " scored " + str(self.score) + " in " + self.subject.title() + "." return full_details def general_bonus(self): """This is a bonus which every student will have.""" print(self.name + " also has a bonus of " + str(self.bonus) + " points.") def update_score(self, final): """Adjusts the original score to the value currently assigned.""" self.score = final student_1 = Students('Jane', 'English Language', '57') student_1.update_score(70) print(student_1.fetch_students_details()) student_1.bonus = 3 student_1.general_bonus() The above is essentially the same program we have been using except for a few additions which we will now explain. We have defined a new method called update_score(self, final) which is to adjust the score to the final value assigned to the student after the continuous assessment.

We programmed this method to replace self.score with final. This means that when we call this method, the value we enclose in the brackets will replace whatever was the value of self.score. Finally, we came to the second line of the last paragraph of the program, where we entered the final score for student_1 by calling the newly defined method, student_1.update_score(70). Python makes the change and produces the output below. Jane scored 70 in English Language. Jane also has a bonus of 3 points. Example 9: Adding to the Value of an Attribute through a Method If we now want to make our computation of the students’ result much neater and much easier to understand, we would want to add the bonus points to the final score. This means that there will no longer be provision for stating the bonus points that a student has separately. We can use the program below to achieve this. class Students(): """This is a step towards modelling a class of students.""" def __init__(self, name, subject, score): """Beginning with name, subject and score attributes.""" self.name = name self.subject = subject self.score = score self.bonus = 5 def fetch_students_details(self):

"""Aim is to retrieve student's name, subject and score.""" full_details = self.name.title() + " scored a total of " + str(self.score) + " in " + self.subject.title() + "." return full_details def update_score(self, final): """Adjusts the original score to the value currently assigned.""" self.score = final def total_points(self, total): """This is the sum of the bonus and the final score.""" self.score += total student_1 = Students('Jane', 'English Language', '57') student_1.update_score(70) student_1.total_points(3) print(student_1.fetch_students_details()) Notice that we simply defined a new method called total_points(self, total) which is to represent the sum of the bonus and the final score. We then programmed the method to add whatever value is in self.score to (+=) whatever value is assigned to total for each student. Finally, we went to the third line of the last paragraph and called this method for student_1 and assigned her bonus points to total (student_1.total_points(3)). Python produces the output below. Jane scored a total of 73 in English Language. Chapter Summary

In this chapter, you have learned what classes are and what operations you can perform using them. You have learned that a class is a set of instructions on how to model specific instances that are related at a general level. You have learned how to add attributes to a class either directly or through the use of methods, and how to print messages by accessing the various methods defined with the classes. Practice with the examples below to further strengthen your knowledge. Exercises 1. Create a class of birds with the attributes of name and color. Next, define two methods, singing, and flying, and use them to instruct Python to print a message about the birds by name stating what activity each bird is engaged in. 2. Create three instances of the class above of birds with different names and colors. Print the same messages about them as you did in the first exercise. 3. You have been recruited by one of the schools in your country to help it produce a database of its teachers. This database is to contain the teachers’ first and last names, gender, age and subject taught. Define a method that prints out a message about each teacher and adds a statement that says the school is proud of him or her. Now, create two instances of this class and call that method using them. 4. Now, suppose that the accounting department of the school has obtained this data base from you and wants you to include each teacher’s current monthly pay. Now, reproduce the program above, adding the attribute teachers_pay, and reprint the messages.

What do you think of the book? Please consider leaving a review herehttp://www.Amazon.com/gp/customer-reviews/write-a-review.html? asin= B07Y8R23CF

CHAPTER FIFTEEN Inheritance: Producing Child Classes from a Parent Class In the previous chapter, you learned how to perform several operations using classes. However, whenever we wanted to perform those operations, we created the class from the scratch. In real life situations, though, it may be time-consuming having to create fresh classes each time you want to perform an operation. Python comes to the rescue and allows you to create child classes from an already-existing class. This is profitable when the new class you want to create has similar attributes to the original class. The child class so created, will retain the attributes of the parent class, and Python makes provision for you to add new attributes to it, modify the attributes inherited from the previous class or even override already-existing classes. This process is called inheritance in Python. Example 1: Creating a Child Class from Students In one of the examples in the last chapter, we created a class called Students, which contained the general attributes that every student should have. In that example, the class was created to show a student’s name, the subject the student sat for in the exam, and the score the student got. Now, suppose that the school in question has begun admitting foreign students. As the schoolteacher, you now wish to create a child class that will deal specifically with them. You want to use a child class because the foreign students still share in the attributes that belong to the rest of the students in the school.

Therefore, rather than start creating a class for them afresh, you want to simply use the parent class, Students, and then add to it the attributes that apply to foreign students, but which do not apply to the rest of the students. The program below shows how to create the child class. class Students(): """This is a step towards modelling a class of students.""" def __init__(self, name, subject, score): """Beginning with name, subject and score attributes.""" self.name = name self.subject = subject self.score = score self.bonus = 5 def fetch_students_details(self): """Aim is to retrieve student's name, subject and score.""" full_details = self.name.title() + " scored a total of " + str(self.score) + " in " + self.subject.title() + "." return full_details def update_score(self, final): """Adjusts the original score to the value currently assigned.""" self.score = final def total_points(self, total): """This is the sum of the bonus and the final score.""" self.score += total

class Foreign_students(Students): """For students who come from other countries.""" def __init__(self, name, subject, score): """This is to begin with the attributes of the parent class.""" super().__init__(name, subject, score) student_2 = Foreign_students('Paul', 'Mathematics', 60) print(student_2.fetch_students_details()) Notice that the program above is the same with that of the examples in the previous chapter except from where we introduced the child class called Foreign_students. Notice that the code class Foreign_students(Students) : has the name of the parent class in brackets. The docstring that follows explains what the child class is about. Next, we defined the __init__(self, name, subject, score) method in order to contain the attributes that all students have. Next is the super().__init__ method which serves to connect the child class with the parent class. Whenever Python sees this, it will call the __init__ method from the parent class. Consequently, any instance created from the child class will inherit all the attributes of the parent class. Now, to test whether this inheritance will really work, we created an instance of Foreign_students which is student_2, whose name is Paul, and who scored 60 in Mathematics. Finally, we call the fetch_students_details() for this instance and ask Python to print it. Look at the output produced below. Paul scored a total of 60 in Mathematics. Example 2: The Child Class and its Attributes

In the previous example, we wrote the program of the parent class, Students, and proceeded to create a child class, Foreign_students from it. Although foreign students have other attributes such as home country that do not apply to all the students, we did not include such attributes in the first example. We only checked to make sure that the child class inherited the attributes of the parent class properly. In this example, we are going to add attributes that are specific to the child class and define methods that will interact with them. We will do that with the program below. class Students(): """This is a step towards modelling a class of students.""" def __init__(self, name, subject, score): """Beginning with name, subject and score attributes.""" self.name = name self.subject = subject self.score = score self.bonus = 5 def fetch_students_details(self): """Aim is to retrieve student's name, subject and score.""" full_details = self.name.title() + " scored a total of " + str(self.score) + " in " + self.subject.title() + "." return full_details def update_score(self, final): """Adjusts the original score to the value currently assigned."""

self.score = final def total_points(self, total): """This is the sum of the bonus and the final score.""" self.score += total

class Foreign_students(Students): """For students who come from other countries.""" def __init__(self, name, subject, score): """This is to begin with the attributes of the parent class.""" """It is also to create attributes of the child class.""" super().__init__(name, subject, score) self.nationality = 'foreign' def students_nationality(self): """Produce a message about each student's nationality.""" print("This student's nationality is " + self.nationality + ".") student_2 = Foreign_students('Paul', 'Mathematics', 60) print(student_2.fetch_students_details()) student_2.students_nationality() In the program above, notice the inclusion of self.nationality = ‘foreign’ under the Foreign_students child class. This adds the new attribute, nationality, and its corresponding value, foreign, to this category of students.

The self at the beginning of the attribute indicates that it is applicable to the child class’s own self and not the parent class. Next, we defined a new method called students_nationality(self). The job of this method is to produce a message about each student’s nationality. Whenever this method is called together with any instance of this child class, it is to print a message that says “This student’s nationality is . . .” and then extracts the nationality indicated from the nationality attribute. Finally, we call the method using the instance, student_2 who is a student named Paul, who scored 60 in Mathematics. Look what output Python has produced. Paul scored a total of 60 in Mathematics. This student’s nationality is foreign. It is up to you to determine how many attributes you wish to add to your child class. However, note that whenever the attribute you wish to add is one that is applicable to all the students, you should add it to the parent class, and only add to the child class if it is specific to it. Example 3: How to Override a Parent Method in the Child Class At the beginning of this chapter, you learned that when you inherit a parent class, you also inherit its attributes, but you are not to worry because you can add your preferred attributes to the child class and override those from the parent class. In this example, we are going to override an attribute from the parent class. However, first, let us consider the code below which contains an attribute called bonus and the corresponding value of 5, in the parent class. class Students(): """This is a step towards modelling a class of students."""

def __init__(self, name, subject, score): """Beginning with name, subject and score attributes.""" self.name = name self.subject = subject self.score = score self.bonus = 5 def fetch_students_details(self): """Aim is to retrieve student's name, subject and score.""" full_details = self.name.title() + " scored a total of " + str(self.score) + " in " + self.subject.title() + "." return full_details def bonus_status(self): """States whether the student has any bonus.""" print("This student has a bonus of " + str(self.bonus) + " points.") class Foreign_students(Students): """For students who come from other countries.""" def __init__(self, name, subject, score): """This is to begin with the attributes of the parent class.""" """It is also to create attributes of the child class.""" super().__init__(name, subject, score) self.nationality = 'foreign'

def students_nationality(self): """Produce a message about each student's nationality.""" print("This student's nationality is " + self.nationality + ".") student_2 = Foreign_students('Paul', 'Mathematics', 60) print(student_2.fetch_students_details()) student_2.students_nationality() student_2.bonus_status() In the program above, we defined a new method called bonus_status which is to state whether the student in question has any bonus. The method is also programmed to print a message that says “This student has a bonus of . . .” and then sates what the bonus is. Finally, we call this method with the instance from the child class called student_2. Look at the output produced by Python as shown below. Paul scored a total of 60 in Mathematics. This student’s nationality is foreign. This student has a bonus of 5 points. Now, supposing your school has a policy of not giving bonus points to foreign students. If you had created a new class, you would simply have omitted the bonus attribute. However, since you only inherited the parent class which contains this attribute also, you will have to override it in the child class. This is what we will do below. class Students(): """This is a step towards modelling a class of students."""

def __init__(self, name, subject, score): """Beginning with name, subject and score attributes.""" self.name = name self.subject = subject self.score = score self.bonus = 5 def fetch_students_details(self): """Aim is to retrieve student's name, subject and score.""" full_details = self.name.title() + " scored a total of " + str(self.score) + " in " + self.subject.title() + "." return full_details def bonus_status(self): """States whether the student has any bonus.""" print("This student has a bonus of " + str(self.bonus) + " points.") class Foreign_students(Students): """For students who come from other countries.""" def __init__(self, name, subject, score): """This is to begin with the attributes of the parent class.""" """It is also to create attributes of the child class.""" super().__init__(name, subject, score) self.nationality = 'foreign'

def students_nationality(self): """Produce a message about each student's nationality.""" print("This student's nationality is " + self.nationality + ".") def bonus_status(self): """Nullifies any bonus claim from foreign students.""" print("Foreign students do not qualify for bonus points.") student_2 = Foreign_students('Paul', 'Mathematics', 60) print(student_2.fetch_students_details()) student_2.students_nationality() student_2.bonus_status()

The program above is similar to the first one in this example. The difference here, however, is the inclusion of a new method under the child class, Foreign_students. This new method is the same bonus_status defined in the parent class. To override an attribute from the parent class in the child class, you need to redefine it. In this example, we redefined this attribute and programmed Python to print a message that notifies whoever is enquiring about bonus marks for foreign students that this group of students do not qualify for bonus marks. Notice that this program contradicts the program associated with bonus_status when it was first defined in the parent class. In Python, this more recent definition automatically overrides all previous definitions. Consequently, where Python printed that the student has a bonus of 5 points, it now prints something else as shown below.

Paul scored a total of 60 in Mathematics. This student’s nationality is foreign. Foreign students do not qualify for bonus points. Example 4: Converting Instances to Attributes In the examples we have been using in this chapter so far, we have created a child class, added attributes to it, and even overridden some methods from the parent class. The child class created above is Foreign_students which has an additional attribute called nationality. Now, in real life situations when you are keeping students’ records in a large school, it may not be enough to just classify the students into citizens and foreign nationals. There may be more classifications needed to be able to better organize how the school manages these students. For example, which specific continents or countries do these foreign students come from? How is their education being sponsored? Do they have insurance cover? What kind of visa do they have? You will notice that all these additional attributes are related to foreign nationals and will differ depending on the specific country from which a student comes. Now, let us further classify the students according to continents into African and European students. Again, suppose that African students do not have scholarships covering full tuition, but have full health insurance cover, which means they must pay for their tuition themselves. Let the European students have both full tuition scholarships and insurance cover. To program all this information as attributes in the class Foreign_students is rather clumsy. We can ease our work by collecting all this information into a separate class called National_details. class Students():

"""This is a step towards modelling a class of students.""" def __init__(self, name, subject, score): """Beginning with name, subject and score attributes.""" self.name = name self.subject = subject self.score = score def fetch_students_details(self): """Aim is to retrieve student's name, subject and score.""" full_details = self.name.title() + " scored a total of " + str(self.score) + " in " + self.subject.title() + "." return full_details class National_details(): """For describing the details of the students' nationality, including their sponsorship.""" def __init__(self, nationality = "foreign"): """This initiates the students' national attributes.""" self.nationality = nationality def describe_national_details(self): """Produce a message about each student's nationality.""" print("This student's nationality is " + self.nationality + ".") class Foreign_students(Students): """For students who come from other countries."""

def __init__(self, name, subject, score): """This is to begin with the attributes of the parent class.""" """It is also to create attributes of the child class.""" super().__init__(name, subject, score) self.national_details = National_details() student_2 = Foreign_students('Paul', 'Mathematics', 60) print(student_2.fetch_students_details()) student_2.national_details.describe_national_details()

In the program above, the code in green color represents the original code in the previous example, which includes the parent class, Students, and the child class, Foreign_students. Follow the code in blue to understand how we rearranged the information about the nationality of the students into a separate class. First, we created a new class entirely called National_details which is to describe the details of the students’ nationality including their sponsorship and health insurance cover. Notice that the brackets in front of the new class are empty, signifying that it is not inheriting anything from any class. You must have noticed since we started creating child classes that each child class has the name of its parent class in the brackets accompanying it. Notice also that this new class is created above the child class, Foreign_students. Next, we defined the __init__() method with nationality = foreign. We programmed it to produce the nationality (which is already defined to be foreign, but can be redefined to be European or African) each time the self.nationality notation is used.

Thereafter, we defined a new method called describe_national_details which is aimed at producing a message about each student’s nationality. We programmed it to print a sentence that says “This student’s nationality is . . .” and then states the student’s nationality as already defined above. Next is the child class, Foreign_students which remains intact except that we coded a self.national_details notation to always refer to the new class, National_details. We

wrote

student_2.national_details.describe_national_details().

Describe_national_details() is a method that prints the message about the student’s nationality. However, since it is not found under the child class, Foreign_students, but under an independent class, National_details, the name of the class is included in the notation. The first part of the notation, student_2 is the identity of the student whose name is Paul and who scored 60 in Mathematics, about whom this message is to be printed. Look at the output produced by Python below. Paul scored a total of 60 in Mathematics. This student’s nationality is foreign. You will notice that this output is the same as the one in Example 2 above. We have simply achieved the same thing using different approaches. In that example, the nationality attribute was under the child class, Foreign_students, and was simply defined as foreign. In this example, nationality has been moved to a separate class called National_details. This is not just for the sake of trying something new. Taking nationality to a new class that focuses on the details of each student’s nationality will enable us to add other attributes related to it in one place. This is to ensure sanity and

order in our programming. Now, in the next example, we will add these attributes. Example 5: Students’ Nationality, Sponsorship and Health Insurance This is the example in which we are going to demonstrate the actual advantage of gathering these details into a separate class, rather than throwing them about as attributes under a larger child class. As we stated in the previous example, we want to code a program that states the scholarship status of these foreign students. Remember, Africans have no scholarships while Europeans have full scholarships. Consider the program below. class Students(): """This is a step towards modelling a class of students.""" def __init__(self, name, subject, score): """Beginning with name, subject and score attributes.""" self.name = name self.subject = subject self.score = score def fetch_students_details(self): """Aim is to retrieve student's name, subject and score.""" full_details = self.name.title() + " scored a total of " + str(self.score) + " in " + self.subject.title() + "." return full_details class National_details(): """For describing the details of the students' nationality, including their scholarship."""

def __init__(self, nationality = "European"): """This initiates the students' national attributes.""" self.nationality = nationality def describe_national_details(self): """Produce a message about each student's nationality.""" print("This student's nationality is " + self.nationality + ".") def get_scholarship(self): """Print a message about the students' scholarship.""" if self.nationality == "European": scholarship = "full" elif self.nationality != "European": scholarship = "nil" statement = "This student is on " + scholarship + " scholarship." print(statement) class Foreign_students(Students): """For students who come from other countries.""" def __init__(self, name, subject, score): """This is to begin with the attributes of the parent class.""" """It is also to create attributes of the child class.""" super().__init__(name, subject, score) self.national_details = National_details() student_2 = Foreign_students('Paul', 'Mathematics', 60)

print(student_2.fetch_students_details()) student_2.national_details.describe_national_details() student_2.national_details.get_scholarship()

In the program above, the parent class, Students; the child class, Foreign_students, and the new class, National_details are retained in green color. The code in blue refers to the areas we worked on to produce our desired output. First, we defined a new method called get_scholarship which is to print information about the student’s scholarship status. Next, we introduced conditional statements. The first statement is that if the student’s nationality is European, then the student has full scholarship. The last statement is that if the student’s nationality is not European, the student has nil scholarship. Thereafter, we introduced a new variable called statement which is a sentence that says “This student is on. . .” and then states the scholarship that the student is on. After that, we asked Python to print this statement each time the method is called in respect to a student. At the bottom of the whole program, we called the get_scholarship method which is under the class, National_details, in respect of a variance, student_2, who is a student named Paul who scored 60 in Mathematics. Now, look what output Python has produced. Paul scored a total of 60 in Mathematics. This student’s nationality is European. This student is on full scholarship.

Apart from the last line in the output which is the statement about the student’s scholarship, notice also that the student’s nationality is now stated as European rather than simply foreign. This is because of a minor adjustment we made in the program above. If you have not already noticed it, you may now go back to the definition of the __init__ method in the National_details class. You will notice that the attribute, nationality, was given the value, European. The practical application of this new program is that each time you want to figure out whether a certain foreign student is on scholarship or not, you simply enter the student’s nationality in that attribute and ask run the program. Straight away, Python will produce the student’s name, subject, score in the subject, nationality, and what scholarship the student is on. Example 6: How to Import Classes By now, you must have already noticed that programming is going to get complicated when you work on real-life situations, especially situations that have large volumes of data. In the examples in this chapter, supposing the number of students was one thousand and their nationalities were equally diverse, you can only imagine the amount of work you would still need to put in processing their information. You must also have noticed that after we define a parent class, most of the operations happening in child classes under it do not require any modification of the parent class itself. Nevertheless, the parent class’s code must always be included. This also applies to child classes. By the time you have defined several classes, the bulk of your program will be taken up by more or less recycled codes that only represent static classes over and over.

To minimize this effect, there is a Provision in Python for programmers to save such classes and import them whenever they need to use them. When these classes are “imported”, they are not really imported in the sense that we would think. The code is not again splashed all over the place, taking up space and time. Instead, by a simple command, Python is instructed to make reference to the parent class whenever necessary. In other words, the desired parent class is simply stated, and Python is informed that whatever program follows is to be interpreted or executed with in addition or with respect to the parent class. In this example, we are going to save the parent class, Students, which we created. Then we are going to attempt to import it and repeat some of the operations we performed with it when it was written live in our program. To do this, first, we need to save the program for the parent class in a separate file. It is advisable to use the name of the class as the file name. By the time you are working with hundreds of classes, you may not remember what name you used in saving each class. To be safe, use the name of the class as the file name. Make sure that the file name has the extension (.py) at the end which lets your text editor know that it is a Python document. From our example in this chapter, the file name is Students.py. At the topmost part of the parent class, you may wish to add a comment describing what this class is about. This too will aid your memory as you start working with several classes. The code will look like what is shown below. #This module contains the program for storing students' information. class Students(): """This is a step towards modelling a class of students."""

def __init__(self, name, subject, score): """Beginning with name, subject and score attributes.""" self.name = name self.subject = subject self.score = score def fetch_students_details(self): """Aim is to retrieve student's name, subject and score.""" full_details = self.name.title() + " scored a total of " + str(self.score) + " in " + self.subject.title() + "." return full_details Whenever you save a program this way, it is referred to as a module. Next, we are going to create a new document into which we will import the parent class we have just saved. This new document may just be an instance of the previous class. Let us call it student_3.py who is a student named Tommy who scored 53 in French. Look at the code below. from Students import Students

student_3 = Students('Tommy', 'French', 53) print(student_3.fetch_students_details())

Python produces the output below. Tommy scored a total of 53 in French.

This is simple, isn’t it? Sure, it is. But that is not all. You can store all the classes you need to work on a particular project in a single module. We are now going to save all the classes we have worked with so far in a single module which we will still call Students.py. At this point, we are talking of the whole program we wrote for those three classes. Just to compare the length, here it is again. class Students(): """This is a step towards modelling a class of students.""" def __init__(self, name, subject, score): """Beginning with name, subject and score attributes.""" self.name = name self.subject = subject self.score = score def fetch_students_details(self): """Aim is to retrieve student's name, subject and score.""" full_details = self.name.title() + " scored a total of " + str(self.score) + " in " + self.subject.title() + "." return full_details class National_details(): """For describing the details of the students' nationality, including their scholarship.""" def __init__(self, nationality = "European"): """This initiates the students' national attributes."""

self.nationality = nationality def describe_national_details(self): """Produce a message about each student's nationality.""" print("This student's nationality is " + self.nationality + ".") def get_scholarship(self): """Print a message about the students' scholarship.""" if self.nationality == "European": scholarship = "full" elif self.nationality != "European": scholarship = "nil" statement = "This student is on " + scholarship + " scholarship." print(statement) class Foreign_students(Students): """For students who come from other countries.""" def __init__(self, name, subject, score): """This is to begin with the attributes of the parent class.""" """It is also to create attributes of the child class.""" super().__init__(name, subject, score) self.national_details = National_details()

Now, we will still open a new document and import only one of the classes into it. This time, we want to also find out Tommy’s nationality and what

scholarship he is on. The code is shown below. from Students import Foreign_students

student_3 = Foreign_students('Tommy', 'French', 53) print(student_3.fetch_students_details()) student_3.national_details.describe_national_details() student_3.national_details.get_scholarship()

Take note in the code above that when we created a new instance of any of the classes, we usually attached the name of the class outside the brackets enclosing the values of that instance. If you do not do this, you will get an error message. Again, look at the output produced by Python below. Tommy scored a total of 53 in French. This student’s nationality is European. This student is on full scholarship . Example 7: How to Import Multiple Classes and Whole Modules In the last example, although we saved multiple classes into the Students.py module, we only imported one of the classes, Foreign_students. In this example, we are going to import two classes from the same module. The code for that is shown below. from Students import Students, Foreign_students

student_3 = Foreign_students('Tommy', 'French', 53)

print(student_3.fetch_students_details()) student_3.national_details.describe_national_details() student_3.national_details.get_scholarship()

Note in the above program that the imported classes are separated by a comma. Everything else including the output is the same as in the above example. You can also import a whole module with its content. So far, we have been only importing the classes in a module by stating their names. Note in the code above that the command for importing the classes in a module starts with from. Now, contrast this with the command for importing a module which starts with import as shown below. Everything else including the output is the same. import Students

student_3 = Students.Foreign_students('Tommy', 'French', 53) print(student_3.fetch_students_details()) student_3.national_details.describe_national_details() student_3.national_details.get_scholarship()

Chapter Summary In this chapter, you have learned the principle of inheritance in working with classes in Python. Inheritance allows you to create a new class, called

the child class, from an already-existing class, called the parent class. After inheriting the parent class, you can modify some of its original attributes, override others, and even create entirely new attributes for your child class. You have also learned how to create new classes to collate attributes that are specific to an instance of another class. This gives you greater leverage to organize your program. Given that programs can be lengthy and sometimes complicated, Python allows you to save your classes into modules and import them using a simple command whenever you need to use them. Now, practice the exercises below. Exercises 1. Suppose that the traffic and road safety regulatory agency in your country intends to create a comprehensive database of all road users in the country. This database is to contain the user’s first and last names, age, and nature of vehicle that the user drives. The agency has hired you to write a program in Python that organizes this database, and prints simple messages describing each road user’s details. Now, write the program by creating a class for it. Next, create two instances of the class above and call them. 2. As an afterthought, the agency also would like you to write a program which in addition to displaying the details of the road user, is able to state whether the user is a traffic offender or not. Not only that, you are also to categorize offenders into first time offenders (zero previous offence) and multiple offenders (at least 1 previous offence). You are to write a program that states at a glance the user’s details and their offence status. Now, write this program by creating a child class called Offenders and using conditional

statements to determine which message to print depending on the number of offences committed. Next, create two instances of the class above and call them. 3. Save the parent and child classes above, and import them into a fresh document, and rewrite the above program.

CHAPTER SIXTEEN

OPERATING WITH FILES So far in our programming journey, we have not really delved into files and locations on our computer. However, in real life, the Python program does not work in isolation but in the midst of several files and file types. A huge quantity of information exists in text files today. Being able to access these files in Python is important. There are a number of options that exist for accessing or reading a text file in Python. In the examples that follow, we are going to take a closer look at the options. Example 1: How to Read a Whole File Note that the file we are going to read is an already-existing file. For the purpose of this example, we are going to create it afresh. However, this principle applies to virtually any kind of text. Kindly type the short poem below into a text editor and save with any name you can remember. In this example, we will use the file name, chapter_15. Save this file in the same location as the one your current Python file is saved in. In this case, we created a folder on the desktop of the computer and saved the current Python file in it. That is also where we will save the text document. The poem to be saved is shown below. There was a dull boy in our class Who swore At all costs I must pass He read himself blind And cluttered up his mind with pills And was the bottom of the class

If you are using Microsoft Word, make sure you save the document as plain text. You will be warned that if you save it as plain text, all your pictures and formatting preferences will be lost. Do not bother about this. Just save it as plain text. Now, return to the Python document you are working on and enter the code below. with open('test.txt') as file_output: contents = file_output.read() print(contents)

The open() function is the command that enables Python to open the file enclosed in the brackets for any kind of operation at all to happen. Without first opening the file this way, no operation can be performed on it. When you issue this command, Python will search the location of the current Python file for the text document you specified in the brackets. When Python finds the document, it saves its content in file_output. There is nothing special about this name. You can use anything you want to use. The read() method enables Python to read the content of the file, and print it following the print() command in the last line. The output is shown below. There was a dull boy in our class Who swore At all costs I must pass He read himself blind And cluttered up his mind with pills And was the bottom of the class

Example 2: Reading a Text File from a Distant Location In the example above, we read the poem contained in the document test.txt. In the code we wrote, we only had to specify the file’s name. This is not the case all the time except when the file to be read is saved in the same location as the Python document you are using to read it. If this is not so and the file is stored in a separate location from where the Python document you are using is saved, you will need to provide Python with a detailed address of the file you wish to open. This address is called the file path. To get the file path of the document, simply open the folder where it is saved, that is, open the various locations until you can see the file. When you do, click on that rectangle on the top which contains the name of the current folder or destination. The moment you do, the file path will be highlighted. To test this, we are going to write another poem and save it in a different location from the one occupied by the current Python file. We are going to save it in a folder called text_folder in the location on the computer called documents. The poem is contained below. Mathew, Mark, Luke and John Bless the bed that I lie on Before I lay me down to sleep I pray the Lord my soul to keep Having saved the poem in that folder, we will copy its file path on my PC. C:\Users\USER\Documents\test_folder\text_2.txt. Now, if your operating system is Windows, change the slashes to back slash, which makes the file

path now read as C:/Users/USER/Documents/test_folder/text_2.txt. Note that the file path will only lead you into the location of the file. However, to enable Python to read the file, attach the file name with the .txt extension at the end of the file path. You can now enter the code below to allow Python to read the content of the file. with open("C:/Users/USER/Documents/test_folder/text_2.txt") file_output:

as

contents = file_output.read() print(contents) Python produces the output shown below. Mathew, Mark, Luke and John Bless the bed that I lie on Before I lay me down to sleep I pray the Lord my soul to keep Because of the length of the file path, you have the option of creating a variable for it and then asking python to open it using the variable name. The code will appear as shown below, but the output will be the same. file_location = "C:/Users/USER/Documents/test_folder/text_2.txt" with open(file_location) as file_output: contents = file_output.read() print(contents)

Example 3: Replacing a Word in a File you are Reading

There are several advantages for being able to open and read text in Python. These advantages span all kinds of texts including words and numerical figures. In our examples so far, we have dealt only with words. One of the advantages of having access to text is the ability to perform a quick editing task on it using the replace() function. In the poem in the last example, we will now use this function to replace John with Peter. Study the code below. file_location = "C:/Users/USER/Documents/test_folder/text_2.txt" with open(file_location) as file_output: contents = file_output.read() output = contents.replace("John", "Peter") print(output) We defined a new variable called output which is defined as contents.replace(“John”, “Peter”). This simply means Python is to access the contents of the file and replace John with Peter. Next, we asked Python to print the output which is shown below. Mathew, Mark, Luke and Peter Bless the bed that I lie on Before I lay me down to sleep I pray the Lord my soul to keep Example 4: How to Write into a Text File In the last three examples, you learned how to access and read a document that already exists on your computer. Another interesting thing with Python

is that it also allows you to write text into an already existing file or a new file altogether. In this example, we are going to write two sentences into a file. Note that we are only writing into the file. We are not asking Python to print the text. Therefore, you will not see the text display anywhere, but if you open the file, you will find this text in it. Again, you can actually ask Python to read the text and display it. The code is shown below. file_name = 'experimental.txt'

with open ('file_name', 'w') as file_output: file_output.write("Nothing serious going on here.") file_output.write("Just experimenting with this code.") When you run this code in Python, Python does not display anything on the screen. Notwithstanding, the file will be created. Note that ‘w’ in the code above instructs Python to open the file in the write mode to enable you write into it. Also, note the .write() method that is added to the file_output. Contrast it with the .read() when we are reading a file. You should exercise caution with this approach if the file in question already exists and has content, as its entire content will be overwritten. Next, we will ask Python to read this file so that we can see whether it was truly created. To do this, we will add the code below to the one above. with open ('file_name', 'r') as file_output: output = file_output.read() print(output)

Note that the above code is not an isolated code. It had to go together with the one that created the file. Note also the ‘r’ in the brackets following the open() function. This means you want Python to open the file in a read mode. The .read() method is attached to the file_ouput for the same purpose. Now, look at the output produced by Python below. Nothing serious going on here. Just experimenting with this code. Go through the code above that created the file. You will notice that these sentences were typed on separate lines. However, Python still wrote them on a single line. To make Python write them on separate lines, we are going to use the line command (\n). See the code and the corresponding output below. file_name = 'experimental.txt'

with open ('file_name', 'w') as file_output: file_output.write("Nothing serious going on here.\n") file_output.write("Just experimenting with this code.\n") with open ('file_name', 'r') as file_output: output = file_output.read() print(output) Nothing serious going on here. Just experimenting with this code.

Another scenario is when you want to write into a text file without overwriting its original content. To do this, we use the append mode to open

the file. We will open the file we created above and add some text to it. The code is shown below. file_name = 'experimental.txt'

with open ('file_name', 'a') as file_output: file_output.write("Anyway, coding is a bit more serious than I thought.\n") with open ('file_name', 'r') as file_output: output = file_output.read() print(output) Note the ‘a’ in the brackets following the open() function. This tells Python that we want to open the file in append mode. The next line of code simply writes the sentence enclosed in quotation marks. Now, look at the output below. Nothing serious going on here. Just experimenting with this code. Anyway, coding is a bit more serious than I thought.

Chapter Summary In this chapter, you have learned how to access text files on your computer using Python. To access a file in a location separate from the location of the Python file you are working in, you would have to specify the file path. Files can be accessed in the read, write or append modes. Practice what you have learned using the exercise below.

Exercise Create an arbitrary text file and replicate the programs above from the first to the last example in this chapter.

CHAPTER SEVENTEEN

MANAGING ERRORS WITH EXCEPTIONS Often, as users interact with your programs, they will encounter some errors. These errors may be due to inappropriate coding on your part or inappropriate input on the part of the user. In either case, Python will display an error message. From our examples and exercises so far, you must have already seen more than a fair share of those kinds of errors. We want to do something about these errors because, first of all, the way Python displays them is not kind on the eyes, and secondly, they reveal too much information which may make your program vulnerable to malicious users who are knowledgeable in programming. This is where the concept of exceptions comes in. It simply means programming ahead of time what Python should do when an error occurs. In this chapter, we are going to show how this can be done. Example 1: Correcting the Value Error print("Just enter any two numbers here, and I will multiply them and return the answer.") print("To exit, just type 'e'.")

while True: number_one = input("\nNumber one: ") if number_one == 'e': break number_two = input("\nNumber two: ")

if number_two == 'e': break

outcome = int(number_one) * int(number_two) print("Answer: " + str(outcome)) This program is designed to perform the multiplication of any two values which the use will input. The user is free to exit at any point by entering ‘e’. The while True: at the beginning of the second block of code is an argument that instructs Python to continue to run the program as long as the user continues to input number_one and number_two. However, where the user inputs ‘e’, Python is to break end the program. The last paragraph of the code is the part that does the calculation and relays it in the variable, outcome. We programmed Python to print the answer. If the user enters 3 and 5 in the first and second places respectively, Python produces the output shown below. Just enter any two numbers here, and I will multiply them and return the answer. To exit, just type ‘e’. Number one: 3 Number two: 5 Answer: 15 Now, this program runs faithfully as long as the conditions defined above are followed. However, when this program is released to the public for their consumption, some people may enter values that are not figures. This

returns an error message in Python. Let us see the error message when a user enters a word in one of the fields. Just enter any two numbers here, and I will multiply them and return the answer. To exit, just type ‘e’.

Number one: 3 Number two: angel Traceback (most recent call last): File “chapter_15.py”, line 12 in Outcome = int(number_one) * int(number_two) ValueError: invalid literal for int() with base 10 : ‘angel’ Now, can you see how unsightly the above error message is? However, we can add an exception to program Python to display a nicer message to the user. Not only that, you must also have noticed that once this error occurs, the entire program stops running. This does not have to be so. We can also make Python give the users another chance after telling them what error they are committing. Study the program below. print("Just enter any two numbers here, and I will multiply them and return the answer.") print("To exit, just type 'e'.")

while True: try:

number_one = input("\nNumber one: ") if number_one == 'e': break number_two = input("\nNumber two: ") if number_two == 'e': break

outcome = int(number_one) * int(number_two) print("Answer: " + str(outcome)) except ValueError: print("Oops! You can only enter numerical figures.") Notice that the program above is essentially the same with the previous one. The only additions are the ones in blue color. Try makes room for another trial when an error occurs. This way, the program does not crash just because of an error. The except ValueError tells Python to print the sentence enclosed in the quotation marks in the brackets. After printing this message, the program continues to run so that the users can learn their lessons and continue with the program. See the output this time as shown below. Just enter any two numbers here, and I will multiply them and return the answer. To exit, just type ‘e’.

Number one: 3

Number two: 4 Answer: 12

Number one: 3 Number two: love Oops! You can only enter numerical figures.

Number one: Example 2: Ignoring Errors In the example above, when we added an exception to the ValueError, we programmed Python to print a statement. However, if we choose to, we can simply program Python to ignore the error and continue with the next trial. This is done using pass. The code and the output are shown below. print("Just enter any two numbers here, and I will multiply them and return the answer.") print("To exit, just type 'e'.")

while True: try: number_one = input("\nNumber one: ") if number_one == 'e': break number_two = input("\nNumber two: ")

if number_two == 'e': break

outcome = int(number_one) * int(number_two) print("Answer: " + str(outcome)) except ValueError: pass Notice that the only addition to this code is pass. See the output below. Just enter any two numbers here, and I will multiply them and return the answer. To exit, just type ‘e’.

Number one: 4 Number two: 3 Answer: 12

Number one: 3 Number two: me

Number one:

Chapter Summary

In this chapter, you have learned how to use exception to display more userfriendly error messages when a program gets into trouble while running. This often happens with programs requiring user input. The principle is the same notwithstanding the kind or error. Exercise Write a program for a simple mathematical operation that runs for as long as the user does not exit and continues to make input available. Let the program also continue running even after a user has made an error. Use an exception to print an error message, describing to the user what kind of error has been made.

CHAPTER EIGHTEEN

HOW EVERYTHING COMES TOGETHER IN PROJECTS By now, you must have already begun to see the potential of how you can deploy your knowledge of Python. There is really no limit to where and what you can use Python to do. In this chapter, we are going to give you picture of how everything you have learned so far can be brought together in one project.

Organization Programming is pretty much like arts. Although there are basic rules that each programming language has and which programmers must adhere to, what project can be done is essentially a matter of each programmer’s creativity. Therefore, to begin with, you need to organize yourself. You need to draw up a plan of what you want to achieve. If it is an online game, for example, you need to decide what kind of game you would like to program. Organizing yourself also involves having a general picture of what the end result of your project is to look like. How is the project supposed to behave? This is important because it will make it easier for you to decide which approach to adopt while writing the program. It is also important to ask yourself how the project is not supposed to behave. This will help you know which approach you are not to adopt while writing the program. Strategy After deciding what you want to achieve, you need to develop a more detailed (preferably written) strategy for achieving it. Your strategy should

contain a breakdown of the project into smaller tasks and the specific program you will use to achieve those tasks. This has several advantages. First, it will make it clearer to you what exactly your project will involve in terms of writing the program and even how much time it may take. Second, it will enable you work on the project in smaller milestones. Achieving these milestones will encourage you to go on and will also enable you to measure your progress. Third, when you have written pages of code especially while working on a huge project, it will still be easy for you to identify a particular segment that needs a certain modification in order to achieve a new goal. Also, if the project malfunctions, you will be able to track where the challenge is likely from. Writing the Program Now that you have a strategy, it will be time to start writing the program for the project. Usually, you should start with the simplest codes and simplest tasks. At the beginning, your speed and your enthusiasm may be high. However, as you make progress, you may get stuck or even bored. At such moments, you need to realize that you probably need to take a break and have some rest. This is true of any project however it’s especially true in coding. When your mind is refreshed and your excitement has returned, you can continue again. In writing the program, you should be open-minded. First, there are a few alternatives to achieving any particular task in Python. As you follow a particular route, it may become necessary for you to modify it, combine it with another or even discard it and start afresh. These are all simply possibilities. Second, you are free to try your hands in any direction you choose. You are the programmer here and the choice of how to execute your project is yours. You will be surprised to learn that you are making

discoveries about which other ways you can achieve the same tasks, without ever knowing before then that such possibilities exist.

Making the Project Accessible to Others After preparing a wonderful program for your project, you still have to figure out how others can use this project. This is important because what you have is essentially a body of code which will not make much sense to someone who does not understand programming. To be able to make the output what the general public can interact with, there is one more thing to do. You need to download the appropriate tool from Python which will enable you process your project in a manner that the lay public can interact with. You can use Python to create computer games, mobile applications, websites, and so on. While the principle is the same, each of these projects requires certain tools which you can download from Python for free. You can find useful links to these tools at the end of the book.

CONCLUSION Having come to the end of this book, you have seen for yourself how varied and interesting the Python language is. Throughout this book you will have made mistakes but remember that is the way to learn. We get better at anything by learning from our mistakes. By now, your confidence level should be high especially if you started as a complete beginner. You may now realize that programming is not as fearful or as difficult as you probably though it was. You have also realized that programming language is applied in pretty every sector of life and is not just limited to building mobile applications and websites. It is important to emphasize here that how you use this book will determine your success with Python. If you are a fresh beginner, you may be frightened by whatever you have heard about programming languages generally. You may also be intimidated by the length of the codes especially in the later chapters. You may even doubt whether you are ever going to master the use of this programming language. However, if you follow the advice in the introduction on how to use the book, you will surely be on top of your game. I hope you are not like those who take a book, scroll through to the end and simply give up without ever reading one complete page! I hope you are not reading this conclusion without first diligently going through the introduction and the chapters that are contained in the book. No one will learn Python that way. You will learn it by doing it repeatedly and practicing as much as possible.

Like was already said in the introduction, one way to make learning fun is to imagine scenarios that may occur in your preferred sector and use them as avenues to apply the language you are learning, solving those issues. Python has an almost unlimited scope of application. However, everyone that learns it has a few of those areas where they wish to apply Python specifically. Identifying this will help you to appreciate early the relevance of what you are learning. It will also make your learning journey more interesting and your lessons more enduring. With constant practice, wide application of what you have learned, and revision when necessary, you should be on your way to becoming as sophisticated and versatile as any of the renowned programmers you have heard of. Thank you for making it to the end and good luck with your programming. Arthur. Did you like the book? Please consider leaving a review herehttp://www.Amazon.com/gp/customer-reviews/write-a-review.html? asin= B07Y8R23CF

If you enjoyed this book you may also enjoy other books by the same author. Do you want to learn everything that you should know about Bitcoin and Blockchain Technology? You should read Bitcoin and Blockchain Basics by Arthur T Brooks. You can access it here. US link http://www.amazon.com/dp/1088935826 UK link http://www.amazon.co.uk/dp/1088935826

REFERENCES AND RESOURCES 1. Eric, M. (2016). Python Crash Course. No Starch Press, San Francisco. 2. Mark, M. (2017). A Smarter www.asmarterwaytolearn.com

Way

to

Learn

Python.

3. Mark, L. (2009). Learning Python. O’Reilly Media, Inc. http://my.safaribooksonline.com 4. Richard, L. H. (2018). Fundamentals of Python Programming. 5. Wikibooks.org (2013). Non-Programmer’s Tutorial for Python 2.6 6. Andrew, J. (2018). Python: The Ultimate Beginner’s Guide! 7. Guido, V. R. (2018). Python Tutorial. www.python.org

ANSWERS TO THE EXERCISES Chapter One Hope your research was successful. If you are looking to work in a particular sector of human endeavor, then you should narrow your research to that sector. Try to find out in what areas Python may be used in your chosen sector. As you read the book further, you will then train your mind to explore how each new thing you learn may be useful in the particular sector.

Chapter Two 1. Find the code and the output below. public_school_teachers = "James, Bill, Andrew, Hillary" print(public_school_teachers) James, Bill, Andrew, Hillary Later on as you read further in this book, you will learn about lists which are a better way to organize items. For now, we just want you to get familiar with one of Python’s most commonly used keyword – print. 2. The code is the same as above, with the only changes made in the values assigned to the variable. public_school_teachers = "Fred, Todd, Wilson" print(public_school_teachers) Fred, Todd, Wilson Chapter Three

1. The code and the output are shown below. The upper(), title(), and lower() methods will be used in the same program. name = "catherine stone" print(name.upper()) print(name.title()) print(name.lower()) CATHERINE STONE Catherine Stone catherine stone 2. The code and the output are produced below. first_name = "James" last_name = "Bull" full_name = first_name + ' ' + last_name print(full_name) James Bull Did you notice the ‘ ’ between the first_name and second_name in the code above? It is to create space between the first name and second name. Without it, the two names will be joined as shown below. JamesBull 3. The code and the output are produced below. first_name = "James" last_name = "Bull" full_name = first_name + ' ' + last_name

print("My most attractive high school friend was " + full_name + ".") My most attractive high school friend was James Bull. 4. Find the code and the output below. first_name = "James" last_name = "Bull" full_name = first_name + ' ' + last_name

first_name_2 = "Anthony" last_name_2 = "Hills" full_name_2 = first_name_2 + ' ' + last_name_2

first_name_3 = "Francisca" last_name_3 = "Gladstone" full_name_3 = first_name_3 + ' ' + last_name_3

first_name_4 = "Andrew" last_name_4 = "Bill" full_name_4 = first_name + last_name_4

print("My most attractive high school friend was " + full_name + ".") print("My most repulsive high school classmate was " + full_name_2 + ".") print("My most brilliant high school classmate was " + full_name_3 + ".")

print("My funniest high school friend was " + full_name_4 + ".") My most attractive high school friend was James Bull. My most repulsive high school friend was Anthony Hills. My most brilliant high school classmate was Francisca Gladstone. My funniest high school friend was Andrew Bill. 5. Find the code below. The output is the same as in number 3 above. first_name = "James" last_name = "Bull" full_name = first_name + ' ' + last_name message = "My most attractive high school friend was " + full_name + "." print (message) Chapter Four 1. The code and output are shown below. print(6+10) print(50-12) print(16*2) print(32/8) 16 38 32 4.0 2. The code and output are shown below.

customer_1 = "Andrew" age_1 = 50 customer_2 = "James" age_2 = 45 customer_3 = "Candy" age_3 = 34 customer_4 = "Annie" age_4 = 18

message_1 = "Happy " message_2 = "th birthday, " message_3 = ". We love you."

print(message_1 + str(age_1) + message_2 + customer_1 + message_3) print(message_1 + str(age_2) + message_2 + customer_2 + message_3) print(message_1 + str(age_3) + message_2 + customer_3 + message_3) print(message_1 + str(age_4) + message_2 + customer_4 + message_3) Happy 50th birthday, Andrew. We love you. Happy 45th birthday, James. We love you. Happy 34th birthday, Candy. We love you. Happy 18th birthday, Annie. We love you.

Notice that in the program above, we created serial variables for customer and age so that the first customer (customer_1) had the first age (age_1). Next, instead of writing “Happy”, “th birthday” and “We love you” four times while asking Python to print messages for the customer, we decided to create serial variables for them too. Therefore, first part of the message (message_1) + the second part of the message (message_2) + the third part of the message (message_3) give rise to the complete message. This made our job much easier and faster as we simply added the relevant part of the message to the respective customer and age. As you work with Python, you are going to discover several creative ways that make your job faster. It all depends on how creative you can be with your imagination. Chapter Five 1. The only difference between this exercise and the last one is that we will now include comments to show why we are doing what we are doing. Notice that comments will not be displayed in the output. They should be as short and as clear as possible. The code may look like what is shown below. #Create a variable for each customer and the age. customer_1 = "Andrew" age_1 = 50 customer_2 = "James" age_2 = 45 customer_3 = "Candy" age_3 = 34 customer_4 = "Annie"

age_4 = 18

#Create a variable for each part of the birthday message. message_1 = "Happy " message_2 = "th birthday, " message_3 = ". We love you."

#We will now simply add the various parts to compose the messages. print(message_1 + str(age_1) + message_2 + customer_1 + message_3) print(message_1 + str(age_2) + message_2 + customer_2 + message_3) print(message_1 + str(age_3) + message_2 + customer_3 + message_3) print(message_1 + str(age_4) + message_2 + customer_4 + message_3) Chapter Six 1. Let our list be a list of household items. In the code below, we will prepare the list, print it in its original order and in the reverse order, and ask Python to produce the output. house_hold_items = ['knife', 'spoon', 'plate', 'cup', 'table', 'chair','bed', 'pillow', 'mirror', 'brush', 'comb', 'radio'] print(house_hold_items)

print(house_hold_items[-1]) print(house_hold_items[-2]) print(house_hold_items[-3])

print(house_hold_items[-4]) print(house_hold_items[-5]) print(house_hold_items[-6]) print(house_hold_items[-7]) print(house_hold_items[-8]) print(house_hold_items[-9]) print(house_hold_items[-10]) print(house_hold_items[-11]) print(house_hold_items[-12]) ['knife', 'spoon', 'plate', 'cup', 'table', 'chair', 'bed', 'pillow', 'mirror', 'brush', 'comb', 'radio'] radio comb brush mirror pillow bed chair table cup plate spoon

knife 2. Here, we will use the list above and perform all the requested operations at once in the program as shown below. house_hold_items = ['knife', 'spoon', 'plate', 'cup', 'table', 'chair', 'bed', 'pillow', 'mirror', 'brush', 'comb', 'radio'] print(house_hold_items)

house_hold_items.remove('chair') print(house_hold_items)

house_hold_items.append('chair') print(house_hold_items)

house_hold_items.insert(3, 'bucket') print(house_hold_items)

del house_hold_items[1] print(house_hold_items)

house_hold_items.pop() print(house_hold_items) In the code above, note that we printed the original list of household items to enable us compare with what is printed after performing the respective

operations. Next, we removed “chair” from the list. Then, we added the chair back to the end of the list. Thereafter, we inserted “bucket” at the fourth position. Remember that counting starts from zero. Following this, we deleted the second item on the list (spoon). Finally, we popped off the last item on our list (chair). The output is shown below. ['knife', 'spoon', 'plate', 'cup', 'table', 'chair', 'bed', 'pillow', 'mirror', 'brush', 'comb', 'radio'] ['knife', 'spoon', 'plate', 'cup', 'table', 'bed', 'pillow', 'mirror', 'brush', 'comb', 'radio'] ['knife', 'spoon', 'plate', 'cup', 'table', 'bed', 'pillow', 'mirror', 'brush', 'comb', 'radio', 'chair'] ['knife', 'spoon', 'plate', 'cup', ‘bucket’, 'table', 'bed', 'pillow', 'mirror', 'brush', 'comb', 'radio', 'chair'] ['knife', 'plate', 'cup', ‘bucket’, 'table', 'bed', 'pillow', 'mirror', 'brush', 'comb', 'radio', ‘chair’] ['knife', 'plate', 'cup', ‘bucket’, 'table', 'bed', 'pillow', 'mirror', 'brush', 'comb', 'radio'] 3. The code and output are shown below. prisoners = ["Bull", "Bill", "Andy", "Fred", "Jones", "Chris", "Alex", "Tom", "Annie", "Smith"] print(prisoners)

print("The following are the prisoners on parole:") print(prisoners.pop(1))

print(prisoners.pop(3)) print(prisoners.pop(5)) [‘Bull’, ‘Bill’, ‘Andy’, ‘Fred’, ‘Jones’, ‘Chris’, ‘Alex’, ‘Tom’, ‘Annie’, ‘Smith’] The following are the prisoners on parole: Bill Jones Tom You will notice from the output that Python starts the counting from zero, the number one prisoner on the list is Bill. Next, with Bill popped from the list, Python goes back to count from zero again to arrive at the number three prisoner on the current list who is Jones. Now, Jones too is popped of the list. Two prisoners are off the list now. Again, Python starts from zero and arrives at the fifth prisoner on the current list who was number seven on the original list, Tom. Chapter Seven 1. The code for all the stated operations is written below with the output following. favorite_teachers = ['Gladstone', 'Guyon', 'Hagin', 'Bush', 'Guyton'] print(favorite_teachers)

favorite_teachers.sort() print(favorite_teachers)

favorite_teachers.sort(reverse = True) print(favorite_teachers)

favorite_teachers.reverse() print(favorite_teachers) What we have done with the code above is to prepare and print a list of five favorite teachers. Next, we sorted them alphabetically using the sort() method. Thereafter, we reversed the sorted list. Notice that it still stays in its alphabetical order. Finally, we reversed the list one more time using the reverse() method. ['Gladstone', 'Guyon', 'Hagin', 'Bush', 'Guyton'] ['Bush', 'Gladstone', 'Guyon', 'Guyton', 'Hagin'] ['Hagin', 'Guyton', 'Guyon', 'Gladstone', 'Bush'] ['Bush', 'Gladstone', 'Guyon', 'Guyton', 'Hagin'] Chapter Eight 1. Below is how we instruct Python to print a list of Tom’s friends. friends = ['Mary', 'Jane', 'Cynthia'] print("This is a list of Tom's friends:") for name in friends: print(name) This is a list of Tom’s friends: Mary Jane

Cynthia 2. See the code and the output below. friends = ['Mary', 'Jane', 'Cynthia'] for name in friends: print("Hi " + name + ", Tom invites you to his birthday celebration.") Hi Mary, Tom invites you to his birthday celebration. Hi Jane, Tom invites you to his birthday celebration. Hi Cynthia, Tom invites you to his birthday celebration. 3. Find the code and the output below. friends = ['Mary', 'Jane', 'Cynthia'] for name in friends: print("Hi " + name + ", Tom invites you to his birthday celebration.") print("You are all invited.") Hi Mary, Tom invites you to his birthday celebration. Hi Jane, Tom invites you to his birthday celebration. Hi Cynthia, Tom invites you to his birthday celebration. You are all invited. Chapter Nine 1. Let us assume that the lane is for buses, pick-up vans and cars. Now, there are four vehicles currently trying to access the lane. The list below is the list of the vehicles trying to access the lane, current_vehicles. The code that follows is to tell Python what to print for each vehicle. current_vehicles = ['bus', 'pick-up', 'car', 'truck']

for vehicle in current_vehicles: if vehicle == 'bus': print("Access granted.") elif vehicle == 'pick-up': print ("Access granted.") elif vehicle == "car": print("Access granted.") else: print("Access denied. Use the appropriate lane.") See the output below. Access granted. Access granted. Access granted. Access denied. Use the appropriate lane. 2. Now, instead of the allowed vehicles being the current vehicles trying to access the lane, it is the forbidden vehicles that are in current_vehicles. Using the !=, we will program Python to still print a denial message for them. This time, the program reads like this: “For every vehicle in current_vehicles, if the vehicle is not a bus, a pick-up or a car, print. . .” Find the code and the output below. current_vehicles = ['truck', 'tipper', 'tractor' 'car'] for vehicle in current_vehicles: if vehicle != 'bus':

print("Access denied. Use the appropriate lane.") elif vehicle != 'pick-up': print("Access denied. Use the appropriate lane.") elif vehicle != "car": printprint("Access denied. Use the appropriate lane.") Access denied. Use the appropriate lane. Access denied. Use the appropriate lane. Access denied. Use the appropriate lane. 3. We are going to prepare a list of shots the player has made (0, 1, 2, 3). Next, we will use the if and elif statements to program Python to print the appropriate information for the player. See the code and output below. current_shots = ['0', '1', '2', '3'] for shot in current_shots: if shot == '0': print("Welcome, buddy. You have a maximum of 3 shots.") elif shot == '1': print("You now have 2 more shots.") elif shot == '2': print("You now have 1 more shot.") elif shot == '3': print("You no longer have any shot left. Thank you.") For each shot represented in the list of current shots, Python prints the respective message as shown below.

Welcome, buddy. You have a maximum of 3 shots. You now have 2 more shots. You now have 1 more shot. You no longer have any shot left. Thank you. 4.

We will simply add a fourth shot and instruct Python to print a

disqualification message for anyone who fires a fourth time. current_shots = ['0', '1', '2', '3', '4'] for shot in current_shots: if shot == '0': print("Welcome, buddy. You have a maximum of 3 shots.") elif shot == '1': print("You now have 2 more shots.") elif shot == '2': print("You now have 1 more shot.") elif shot == '3': print("You no longer have any shot left. Thank you.") elif shot == '4': print("You are disqualified! You have fired more than 3 shots.") Welcome, buddy. You have a maximum of 3 shots. You now have 2 more shots. You now have 1 more shot. You no longer have any shot left. Thank you.

You are disqualified! You have fired more than 3 shots. 5. We will now program Python to give a warning at the fourth shot and then print a disqualification message for any other shots fired. current_shots = ['0', '1', '2', '3', '4', '5'] for shot in current_shots: if shot == '0': print("Welcome, buddy. You have a maximum of 3 shots.") elif shot == '1': print("You now have 2 more shots.") elif shot == '2': print("You now have 1 more shot.") elif shot == '3': print("You no longer have any shot left. Thank you.") elif shot == '4': print("Last warning: You will be disqualified if you fire again.") else: print("You are disqualified! You have fired more than 3 shots.") Welcome, buddy. You have a maximum of 3 shots. You now have 2 more shots. You now have 1 more shot. You no longer have any shot left. Thank you. Last warning: You will be disqualified if you fire again.

You are disqualified! You have fired more than 3 shots.

Chapter Ten 1. We will just compose a simple dictionary for the inmate. See the code below. inmate_1 = { 'name': 'Jackson', 'age': '23', 'gender': 'male', 'crime': 'rape', 'due_for_release': '3 months', 'option_of_fine': 'none' } print(inmate_1) {'name': 'Jackson', 'age': '23',

'gender': 'male', 'crime': 'rape',

'due_for_release': '3 months', 'option_of_fine': 'none'} 2. See the code below. inmate_1 = { 'name': 'Jackson', 'age': '23', 'gender': 'male',

'crime': 'rape', 'due_for_release': '3 months', 'option_of_fine': 'nil' }

inmate_2 = { 'name': 'Bill', 'age': '40', 'gender': 'male', 'crime': 'murder', 'due_for_release': '1 month', 'option_of_fine': '$10,000' } name_1 = inmate_1['name'] age_1 = inmate_1['age'] gender_1 = inmate_1['gender'] crime_1 = inmate_1['crime'] release_date_1 = inmate_1['due_for_release'] fine_1 = inmate_1['option_of_fine']

name_2 = inmate_2['name'] age_2 = inmate_2['age']

gender_2 = inmate_2['gender'] crime_2 = inmate_2['crime'] release_date_2 = inmate_2['due_for_release'] fine_2 = inmate_2['option_of_fine']

message_1 = name_1 + " is " + "a " + age_1 + " year old " + gender_1 + " " + crime_1 + " convict, who has " + release_date_1 + " left to serve, with " + fine_1 + " option of fine."

message_2 = name_2 + " is " + "a " + age_2 + "year old " + gender_2 + " " + crime_2 + " convict, who has " + release_date_2 + " left to serve, with " + fine_2 + " option of fine."

print(message_1) print(message_2)

First, we created two dictionaries, one for each inmate. Next, we created corresponding variables for each inmate’s details instructing Python to select from the dictionary. Finally, we composed messages using the variables created above, and asked Python to print the messages. Look at the output below. Jackson is a 23 year old male rape convict, who has 3 months left to serve, with nil option of fine.

Bill is a 40 year old male murder convict, who has 1 month left to serve, with $10000 option of fine. 3. First, we prepare a master list of all the prisoners in the jail. Next, we prepare a list of the prisoners who are due for release. Then we prepare a list of those who have been released. We then program Python to go through the lists and identify anyone due for release but who has not been released. We also ask Python to identify anyone who is in jail but who is not due for release yet. There is a message for each category of inmates. See the code below. total_inmates = ['Bill', 'Hagin', 'Fog', 'Steve', 'Murray', 'Tim', 'Frank'] due_inmates = ['Bill', 'Hagin', 'Fog', 'Steve', 'Murray'] released_inmates = ['Bill', 'Hagin', 'Fog', 'Steve']

for inmate in due_inmates: if inmate not in released_inmates: print("We are sorry, " + inmate +"." + " You will be released immediately.") for inmate in total_inmates: if inmate not in due_inmates and released_inmates: print ("Sorry " + inmate + "." + " Your term is still running. Good luck next time.") From the three lists above, you will realize that Murray was actually due for release but was not released hence his name was not among the released inmates. However, Tim and Frank were not yet due for release.

We are sorry, Murray. You will be released immediately. Sorry Tim. Your term is still running. Good luck next time. Sorry Frank. Your term is still running. Good luck next time. 4. First, we create a dictionary of all the prisoners in the country and their due for release status. Next, we create a list of the missing prisoners. Then we program Python to take every prisoner reported missing and search through the dictionary of prisoners. If any of them is found in that dictionary, Python prints a confirmatory message and also states their status. Otherwise, Python reports that they are not in the jail. See the code below. total_inmates = {'Bill': 'due', 'Hagin': 'not yet due' , 'Fog': 'due', 'Steve': 'not yet due', 'Murray': 'not yet due'} missing_inmates = ['Tim', 'Murray', 'Fog'] for inmate in missing_inmates: if inmate in total_inmates: print(inmate + " is actually in our jail.") print("He is " + total_inmates[inmate] + " for release.") else: print(inmate + " was not found in our jail.") Look at the output produced below. Tim was not found in our jail. Murray is actually in our jail. He is not yet due for release.

Fog is actually in our jail. He is due for release. Chapter Eleven Whatever situations you thought of, you should be able to create dictionaries and nest them in a list. If you have any difficulties, refer to the examples in the mother chapter. Chapter Twelve 1. See the code below. display = "Please, enter your name here: "

customers_name = input(display) print("Dear " + customers_name + ", you are welcome to our hotel. Thanks for choosing us.") When the customer is prompted and he enters his name, Python prints a welcome message with his name. See the output below. Please, enter your name here: James Dear James, you are welcome to our hotel. Thanks for choosing us. 2. Here is the code. display = "Dear parent, please enter the item here: " enquiry_item = input(display)

items_on_sale = ["textbooks", "uniforms", "school badges", "exercise books"]

items_for_free = ["socks", "breakfast", "pens", "graph books"]

if enquiry_item in items_on_sale: print("Yes, " + enquiry_item + " are for sale in the school. They are not given free.") elif enquiry_item in items_for_free: print( enquiry_item.title() + " are not sold by the school. They are given free.") else: print("We don't know about this item. Please, send an email to the principal for more details.") The output below is for an item that the school sells, one which is given free, and one for which there is no information. Dear parent, please enter the item here: textbooks Yes, textbooks are for sale in the school. They are not given free. Dear parent, please enter the item here: socks Socks are not sold by the school. They are given free. Dear parent, please enter the item here: pillows We don’t know about this item. Please, send an email to the principal for more details. 3. See the code below. prompt = "Enter the secret code here: "

enquiry = input(prompt)

if enquiry == "333": print("This drug has not expired. It is safe for public use.") else: print("Danger! This drug is no longer safe. Do not buy.") Below is the output for a drug that is safe and for one that is not safe. Enter the secret code here: 333 This drug has not expired. It is safe for public use. Enter the secret code here: 345 Danger! This drug is no longer safe. Do not buy. Chapter Thirteen 1. Here is the code. def bye_bye(): """Print a sweet parting message.""" print("Good bye dear. I will miss you.") bye_bye() See the message below. Good bye dear. I will miss you. 2. Here is the code. def bye_bye(name): """Print a sweet parting message."""

print("Good bye dear " + name + "." + "I will miss you.") bye_bye("Jane") See the message now. Good bye dear Jane. I will miss you. 3. Here is the code. def pupils_poem(name, age, pupils_class, favorite_teacher): """Print a little poem with pupil's details in it.""" print("My name is " + name) print("I am " + str(age) + " years old") print("I am in class " + str(pupils_class)) print("My favorite teacher is " + favorite_teacher) print("I am proud of him")

pupils_poem("Jane", "8", "4", "Ferguson") If you run it, you will get the poem below. My name is Jane I am 8 years old I am in class 4 My favorite teacher is Ferguson I am proud of him 4. We will now call the function above for the three pupils. pupils_poem("Angel", "6", "3", "Hills")

pupils_poem("Smith", "12", "6", "Hagin") pupils_poem("Fred", "9", "5", "Alex") Now, here are the poems. My name is Angel I am 6 years old I am in class 3 My favorite teacher is Hills I am proud of him

My name is Smith I am 12 years old I am in class 6 My favorite teacher is Hagin I am proud of him

My name is Fred I am 9 years old I am in class 5 My favorite teacher is Alex I am proud of him Chapter Fourteen

1. Below is the code. There is no output here because we haven’t created any instance yet. Remember, it is the instance that has specific individual members of the class. class Birds(): """A general class of birds.""" def __init__(name, color): """We begin with attributes of name and color.""" self.name = name self.color = color def flying(self): """Programming a bird which is flying.""" print(self.name + " is flying at the moment.") def singing(self): """Programming a bird to fly.""" print("The " + self.name + " is also singing.") 2. Here are the instances and their respective output. bird_1 = Birds('eagle', 'black') bird_2 = Birds('kite', 'grey') bird_3 = Birds('sparrow', 'blue')

print("The first bird is a " + bird_1.color + " " + bird_1.name + "." ) bird_1.flying()

bird_1.singing()

print("The second bird is a " + bird_2.color + " " + bird_2.name + "." ) bird_2.flying() bird_2.singing()

print("The third bird is a " + bird_3.color + " " + bird_3.name + "." ) bird_3.flying() bird_3.singing() The first bird is a black eagle. The eagle is flying at the moment. The eagle is also singing.

The second bird is a grey kite. The kite is flying at the moment. The kite is also singing.

The third bird is a blue sparrow. The sparrow is flying at the moment. The sparrow is also singing. 3. Your code should look like what we have below.

class Teachers(): """A general class of school teachers.""" def __init__(self, first_name, last_name, gender, age, subject): """We begin with the attributes above.""" self.first_name = first_name self.last_name = last_name self.gender = gender self.age = age self.subject = subject def statement(self): """A statement to describe each school teacher.""" print(self.first_name.title() + " " + self.last_name.title() + ", a" +"" + str(self.age) + " year old " + self.gender + ", is our " + self.subject + " teacher.") print("We are proud of " + self.first_name + ".") teacher_1

=

Teachers("Tim",

"Franks",

"male",

"35",

"mathematics") teacher_2 = Teachers("Ann", "Baker", "female", "28", "English Language")

teacher_1.statement() teacher_2.statement()

And the output is shown below. Tim Franks, a 35 year old male, is our mathematics teacher. We are proud of Tim. Ann Baker, a 28 year old female, is our English Language teacher. We are proud of Ann. 4. The code below is essentially the same as the one above. The additions are in blue, while the original is in green. class Teachers(): """A general class of school teachers.""" def __init__(self, first_name, last_name, gender, age, subject): """We begin with the attributes above.""" self.first_name = first_name self.last_name = last_name self.gender = gender self.age = age self.subject = subject def statement(self): """A statement to describe each school teacher.""" print(self.first_name.title() + " " + self.last_name.title() + ", a" + " " + str(self.age) + " year old " + self.gender + ", is our " + self.subject + " teacher.")

print(self.first_name.title() + "'s pay is " + str(self.pay) + " US dollars.") print("We are proud of " + self.first_name + ".") def teachers_pay(self, pay): """A method to include the teacher's pay.""" self.pay = pay teacher_1 = Teachers("Tim", "Franks", "male", "35", "mathematics") teacher_2 = Teachers("Ann", "Baker", "female", "28", "English Language")

teacher_1.teachers_pay(2000) teacher_2.teachers_pay(2100)

teacher_1.statement() teacher_2.statement() The output is shown below. Tim Franks, a 35 year old male, is our mathematics teacher. Tim’s pay is 2000 US dollars. We are proud of Tim. Ann Baker, a 28 year old female, is our English Language teacher. Ann’s pay is 2100 US dollars. We are proud of Ann.

Chapter Fifteen 1. Here is the code. class RoadUsers(): """A general class of road users in my country.""" def __init__(self, first_name, last_name, age, vehicle): """We begin with the attributes above.""" self.first_name = first_name self.last_name = last_name self.age = age self.vehicle = vehicle def statement(self): """A statement to describe each road user.""" print(self.first_name.title() + " " + self.last_name.title() + ", a" + " " + str(self.age) + " year old " + ", is a " + self.vehicle + " driver.") print(self.first_name + " is law-abiding.") user_1 = RoadUsers("Fred", "Dolphin", "35", "lorry") user_2 = RoadUsers("Andy", "Philips", "28", "taxi")

user_1.statement() user_2.statement() And the output. Fred Dolphin, a 35 year old, is a lorry driver.

Fred is law-abiding. Andy Philips, a 28 year old, is a taxi driver. Andy is law-abiding. 2. Here is the code. class RoadUsers(): """A general class of road users in my country.""" def __init__(self, first_name, last_name, age, vehicle): """We begin with the attributes above.""" self.first_name = first_name self.last_name = last_name self.age = age self.vehicle = vehicle def statement(self): """A statement to describe each road user.""" print(self.first_name.title() + " " + self.last_name.title() + ", a" + " " + str(self.age) + " year old " + ", is a " + self.vehicle + " driver.") class Offenders(RoadUsers): """A class to state the offender status of each road user.""" def

__init__(self,

first_name,

last_name,

age,

previous_offences): """Beginning with the attributes of the parent class.""" super().__init__(first_name, last_name, age, vehicle)

vehicle,

self.status = "offender" self.previous_offences = previous_offences def statement_1(self): """A statement to classify traffic offenders.""" if self.previous_offences is 0: print(self.first_name.title() + " is a first time offender.") elif self.previous_offences > 0: print(self.first_name.title() + " is a multiple offender.")

user_1 = Offenders("John", "Bull", "35", "lorry", 0) user_2 = Offenders("Bill", "Penguin", "28", "taxi", 2)

user_1.statement() user_1.statement_1()

user_2.statement() user_2.statement_1() And below is the output. John Bull, a 35 year old, is a lorry driver. John is a first time offender. Bill Penguin, a 28 year old, is a taxi driver. Bill is a multiple offender.

3. Go ahead and answer the third question. If you have any problems, refer to the examples in the mother chapter. Chapter Sixteen Hope you succeeded. If you have any challenges, refer to the examples in the chapter. Chapter Seventeen You should have something like what is shown below. Of course, you can try out the code yourself and see if it works. print("If you enter any one number, I will multiply them and divide the answer by 3") print("Enter 'c' to close.")

while True: try: first_number = input("\nFirst Number: ") if first_number == 'c': break second_number = input("\nSecond Number: ") if second_number == 'c': break answer = int(first_number) * int(second_number)/3 print("The answer is: " + str(answer)) except ValueError:

print("Sorry! Enter a numerical figure.")

INDEX A addition (+), 13, 16 append() method, 24, 25, 27, 62, 115, argument, 71-74 attributes, 75-76 with a default value, 82 of a child class, 91 converting from instances, 97 B birthday, 15 C calling functions, 70-74 child classes, 89 its attributes, 91 overriding its parent methods, 93 classes, 75-76 comments, 18-19, 61, 130 comparison operators, 78–80 conditional statements, 42, 102, 109

D default value, 82 del statement, 25 dictionaries, 43-58 nesting in a list, 60 modifying in a list, 62 division (/), 13-16 docstring, 70, 76, 81, 90 dot notation, 78, 81 E elif statement, 42, 136 else statement, 42, 66 exceptions, 117 F Files, 5, 110, 116 for loop, 32 in a dictionary, 51 with keys, 52 functions, 68, 70, 73 G Games, 67

Geany, 4, 5, 13 greater than, 66 greeting, 6 H hash sign (#), 18, 61 Hello everyone, 5-7 I Installation, 4 if statements, 34, 42 inequality, 36 items, 20-28 import, 103 multiple classes, 107 inheritance, 89, 91 input() function, 65 insert() method, 25 int() function, 66 items() method, 52 K keys, 53 L len() function, 29

lists, 20, 28 nesting dictionaries in, 60 lower() method, 126 M methods, 9 in a class, 78 modules, 107 multiplication, 13 N Nesting, 60 newline (\n), 67 numbers, 13-14 O open() function, 111, 114-115 P parameters, 72 parent class, 89-108 pop(), 25-27 positional, 72 print(), 111 prompts, 65 projects, 1, 60, 75, 122

Q quit, 68 R range() function 62 read() method, 111, 114 S sorted() function, 28 sort(), 29, 133-134 square brackets, 20-21, 43 str() function, 14-15 strings, 9 concatenating, 10 subtraction, 13, T text editor, 2, 4 title() method, 9, 71, 73 U upper(), 9, 34 V Values, 6 in a dictionary, 57

values() method, 57 variables, 6 W while loops, 65, 67 write() method, 114