0% found this document useful (0 votes)
16 views83 pages

Python-3 Coding 165pgs

This document is a comprehensive guide for beginners to learn coding in Python, covering installation, variables, data types, lists, conditionals, functions, and object-oriented programming. It provides step-by-step instructions and practical examples to help readers understand and apply Python concepts effectively. The guide is structured in chapters, each focusing on specific topics, making it accessible for those starting from scratch.

Uploaded by

swaceke1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views83 pages

Python-3 Coding 165pgs

This document is a comprehensive guide for beginners to learn coding in Python, covering installation, variables, data types, lists, conditionals, functions, and object-oriented programming. It provides step-by-step instructions and practical examples to help readers understand and apply Python concepts effectively. The guide is structured in chapters, each focusing on specific topics, making it accessible for those starting from scratch.

Uploaded by

swaceke1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Coding in Python

A Comprehensive Beginners Guide to Learn


the Realms of Coding in Python
Table of Contents If Statements and Lists
Introduction Multiple Lists

Chapter One: Make a Start Chapter Five: Python Dictionaries


Python 3 Installation Removing Pairs
Executable Installer Looping
Run It The sorted() Method
Nesting
Chapter Two: Python Variables and Data Types
Random Dictionary Methods
Python Variables
Naming Variables Chapter Six: Input and Python Loops
Python Datatypes The input() Function
Python Strings While Loops
Python Numbers The Break Keyword
Chapter Three: Python Lists and Tuples Loops, Lists, Dictionaries
Modifying Lists Chapter Seven: Python Functions
Append Method
Defining Functions
Del Method
Pop Method Arguments and Parameters
Remove Method Positional Arguments
List Organization Keyword Arguments
The sort() Method Default Values
Index Errors
Returning Values
Create A Loop
List Slicing Function and Dictionary
Copying Function and While Loop
Python Tuples Chapter Eight: Object-Oriented Programming
Looping Leopard Class
Chapter Four: Python Conditionals Explaining the __init__() Method
The if-else Statement The Fish Class
The if-elif-else Chain The Bike Class
Proper Modification of Values © Copyright 2020 by Robert C. Matthews - All rights reserved.
This document is geared towards providing exact and reliable information in regards to the topic and
Chapter Nine: The Inheritance Class issue covered. The publication is sold with the idea that the publisher is not required to render
accounting, officially permitted, or otherwise, qualified services. If advice is necessary, legal or
Child Class in Python 2.7 professional, a practiced individual in the profession should be ordered.
Child Class Attributes - From a Declaration of Principles which was accepted and approved equally by a Committee of the
American Bar Association and a Committee of Publishers and Associations.
Overriding Methods from Parent Class
In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronic
Chapter Ten: Importing Classes means or in printed format. Recording of this publication is strictly prohibited and any storage of this
document is not allowed unless with written permission from the publisher. All rights reserved.
Importing Multiple Classes The information provided herein is stated to be truthful and consistent, in that any liability, in terms of
inattention or otherwise, by any usage or abuse of any policies, processes, or directions contained
Importing Module within is the solitary and utter responsibility of the recipient reader. Under no circumstances will any
legal responsibility or blame be held against the publisher for any reparation, damages, or monetary
Importing All Classes loss due to the information herein, either directly or indirectly.
Conclusion Respective authors own all copyrights not held by the publisher.
The information herein is offered for informational purposes solely, and is universal as so. The
References presentation of the information is without contract or any type of guarantee assurance.
The trademarks that are used are without any consent, and the publication of the trademark is without
permission or backing by the trademark owner. All trademarks and brands within this book are for
clarifying purposes only and are the owned by the owners themselves, not affiliated with this
document.
Introduction I have clearly written the codes. Each code is coupled with its results. You
can copy the code and paste it in the editor, do the edits of your choice, and
get the result. This is how you can easily learn to code. I have written all the
This book contains proven steps and strategies on how to code in Python. In codes in Python 3.8 which is why I recommend you to download and install
this book, I have included all the basics of coding in Python, written in a it. The process is already made a part of this book.
lucid and easy-to-digest form. The book is divided into different chapters,
each dealing with a specific topic. I started the book by explaining the I wrote this book with the goal that a person who has to start Python coding
process of downloading and installing Python on your operating system. As from scratch can easily learn to code. The book is for those who are just
Windows is the most popular operating system in the world, I focused on getting started. I have explained each concept with due depth and
Python installation on Windows. comprehensiveness so that you beginners can understand it and digest it well.
Even if you are just getting started in the world of coding, you can easily
After that, I moved on to Python variables and data types. I have explained understand the concepts.
them one by one. The most interesting of all the datatypes is the Python
string, and it also is the most widely used in different Python programs that I recommend that you keep a notebook and a pen with you when you read
you will find in this book and that you will create yourself. Therefore, I this book so that you can note down the important points and code syntax to
emphasized it. Then I moved on to Python lists and tuples. I have tried to remember them and practice them. You also can bookmark them on a smart
create a story in the book so that you find the content coherent, juicy, and device and jump to the desired pages when you want to read them. Unlike
highly valuable. To fulfill this purpose, I have created a game zone that is other dry books of coding, this book will explain each step of the code so that
under development. The game revolves around a player who has a mission to you can easily reproduce what you have learned. I hope you have fun reading
equip an office with the cheapest in terms of price and with the most needed sessions once you get started. If you have got the fire to learn Python, this
items so that the player can sell the office to the highest bidder. You can see book should finish in five to six reading sessions.
the story kicking off with the start of the section on lists and tuples.
I will explain different Python codes regarding the game. As you find
yourself inside the game development, you will learn different list methods
such as the del method, the pop method, and list slicing. The game then
moves on toward Python conditionals and dictionaries and gets more
interesting. The conditionals add logic to the game, and dictionaries offer a
way to store data most efficiently.
One of the most interesting programs you will see invites user input and
integrates it into a while loop. You will also enjoy the chapter on functions
that make the code smart and highly engaging. Functions are interesting
because they can be easily paired up with different data types, and for and
while loops.
Object-oriented programming will introduce to real programming. You will
learn how to create classes, inheritance classes, and model real-life objects
with the help of programming. You can create some very interesting
programs with the help of Python classes.
Chapter One: Make a Start You should download and install Python executable installer on your
Windows operating system. The first step in this regard is to open your
internet browser and move to the Downloads section of [Link]. Make
This chapter will walk you through the process of making a start in Python sure that you download and install only the version that has an executable
coding. You will learn how to download and install Python on your operating installer available for Windows. The approximate download size is about 25
system. You will also learn how to start the editor and write a code in Python MB. If your Windows is a 32-bit operating system, you should select
text editor. Windows x86 executable installer. If it is 64-bit, you should select Windows
The first thing you should know about is setting up a Python environment on x86-64 executable installer. However, even if you install the wrong version,
your operating system. Python is installed differently on different operating it is easy to uninstall it and reinstall it once again.
systems. There are currently two available versions of Python which are Run It
Python 2 and Python 3. Each programming language keeps evolving as
developers add to it new concepts and ideas. Python developers have taken a When the executable installer of Python has been downloaded, you need to
step further by making regular developments to the language, making it more run it. Select Install launcher for all users. This will ensure that all users on
powerful and versatile as well. You can install both versions of your your system will be able to use it. Don’t forget to tick Add Python 3.8 to the
operating system. PATH box. This links the interpreter to the path of execution and facilitates
programming. Older versions don’t display this option.
Python 3 Installation
In the next step, click on Install Now. When you have installed it, you will
Python is one of the most widely used programming languages that were first see that you will get Python IDLE and Pip. You also can verify Python on
launched in 1991. Since then Python has gained immense popularity. It also your system by navigating to the directory in which Python was installed or
is considered one of the most popular as well as flexible programming by entering the word Python in the search bar. You also can check it through
languages. Unlike Linux, Windows operating systems don’t have Python pre- Command Prompt by the name of the directory.
installed by default. However, you always can install Python on the Windows
operating system is a very easy step. If you opt to install Python 2, you might not get Pip installed with it. Pip is a
powerful package and is very helpful in building software and machine
The prerequisites of installing Python 3 on your Windows system are that learning models. Therefore, you should make sure that the version you have
you must have Windows 10 installed on the system and have admin installed has got Pip installed on it.
privileges. Also, you should have a command prompt running on the system.
The next prerequisite is the availability of a remote desktop app. You can use You can also confirm if Pip is installed on your operating system or not by
it if you are planning to install Python on a remote Windows server. opening the Start menu and typing the word cmb in the search bar. The
command will open the Command Prompt application in which you can write
The first step in the installation process is selecting the version you want to pip –v. If the pip is installed on your system, you will see a line that starts
install. In this case, we are aiming at downloading Python 3. You should visit with pip 19.0.3. Otherwise, the system will say that it doesn’t recognize pip
the official Python website [Link] and download Python 3 installer for as an external or internal command. When you open the Python interpreter or
Windows. Now run the same on your system. As you are just getting started IDLE, it will have text like the following:
on learning the Python language, I recommend that you download and install
Python 2 and Python 3 versions to test old and new projects simultaneously. Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64
bit (AMD64)] on win32
Executable Installer
Type "help", "copyright", "credits" or "license()" for more information.
>>> Chapter Two: Python Variables and Data Types
On the top is written the version of Python. If you have installed Python 2, When you run a file with the extension .py on Python, it suggests that you are
the text will be as follows:
running a Python program. The editor runs the program in a Python
Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] interpreter. The Python interpreter spots Python keywords, reads them,
on win32 identifies them, and acts accordingly. Take the example of the print keyword.
Type "copyright", "credits" or "license()" for more information. When the Python interpreter sees this keyword, it can print whatever you put
in the parenthesis. When you write code in the Python editor, you will see
>>> that the Python editor highlights your code in different colors. That is how it
recognizes different types of code. This feature of Python is known as syntax
highlighting and is very useful as you learn to write Python programs.
Python Variables
Python variables are like containers that you can fill in with different types of
data values. Python differs from other programming languages because it
does not have any command for the declaration of a variable. You can create
a variable just by assigning it a specific value. In the following example, I
will create a variable and assign it some value. Please keep in mind that I am
using a Python interpreter for the initial stages. I will move on to the Python
editor in the later chapters.
>>> greetings = "Hello, I am here to learn Python."
>>> print(greetings)
Hello, I am here to learn Python.
>>>
The name of the variable is greetings. The variable holds a full sentence as its
unique value. The print keyword, as I said, is used to display the value of the
variable. The value of a variable can be easily replaced if you pack it up with
another value. See the following example.
>>> greetings = "Hello, I am here to learn Python."
>>> print(greetings)
Hello, I am here to learn Python.
>>>
>>> greetings = "This is the world of Python."
>>> print(greetings) Traceback (most recent call last):
This is the world of Python. File "<pyshell#6>", line 1, in <module>
>>> print(greeting)
Naming Variables NameError: name 'greeting' is not defined
When you are naming a variable, you must adhere to a couple of guidelines >>>
and rules. If you break some of the rules, you will see errors in the code. All I did was writing the wrong spelling in the code. What makes Python
Even if missing out on the rules does not trigger errors, breaking the rules
different from other programming languages is that it displays the error
will make the code look vague and abstract. The success of a programmer is message which tells you the exact line on which you have made the error.
that his code should be easy to understand and read. You must keep the This helps rectify the errors and clean the code.
following rules in mind when you are creating variables.
By writing the wrong spelling, I don’t suggest that Python recognizes the
The names of variables may contain numbers, letters, and wrong or right spelling. I am trying to suggest that it reads the name of the
underscores. They may start with an underscore and a letter, but variable and matches it with the command you have entered. In case of a
they cannot start with a number. For example, a variable can be mismatch, the error message pops up. So, even if you misspell the word
written as greetings_77 but it cannot be written as 77_greetings. while you allot a name to a variable, Python does not declare it an error.
You must avoid the use of Python keywords while naming a >>> greetings = "This is the world of Python."
variable. For example, you cannot name a variable as print >>> print(gretings)
because print is a Python keyword.
This is the world of Python.
If you can keep the names of variables as much descriptive as
possible, it will help you better read and understand the code when >>>
you come back to at a later stage. For example, greetings are I have deliberately misspelled the word greetings but still, Python read it and
better than simply writing g. ran the code. A lot of programming errors happen just because of wrong
Writing variable names is a continuous practice in Python. You will learn spellings. You may call them typos. They can be easily managed if you read
how to create better variable names as you move further into the world of your code with close attention.
coding. Python Datatypes
When you are creating variables, it is common to get errors. You should There are different types of data that you have to use in programming. Some
make sure that you are not misspelling different words. Take a look at the are simple texts while others are integers or lists. Python supports a diversity
possible errors and try to learn how to avoid them and fix them. of datatypes. However, you have to designate the datatype when you create
I will use the same variable greetings to show how you can end up getting an one so that Python can recognize it easily and process it as per your wishes.
error message. In the following section, I will shed light on several data types that I will be
using in various code snippets in the book.
>>> greetings = "This is the world of Python."
Datatypes, in a brief look, are as under:
>>> print(greeting)
#This is Python list
>>> a = ["tomato, potato, garlic, ginger, pumpkin"] "ginger", "veg3" : "pumpkin"}
>>> print(a) >>> print(a)
['tomato, potato, garlic, ginger, pumpkin'] {'fruit': 'tomato', 'veg': 'potato', 'veg1': 'garlic', 'veg2': 'ginger', 'veg3':
'pumpkin'}
>>> #This is python frozenset
>>> a = frozenset({"tomato, potato, garlic, ginger, pumpkin"}) In the above I have turned a string into different datatypes. In the dictionary
section of the code, you will see some errors. One error is because of a
>>> print(a) missing quote marks while the other error is because of similar dictionary
frozenset({'tomato, potato, garlic, ginger, pumpkin'}) names. Dictionaries are important as they allow users to store their important
data in the form of pairs. They are used in a number of ways.
>>> #This is python set
Python Strings
>>> a = {"tomato, potato, garlic, ginger, pumpkin"}
The first data type is Python strings. Most of the Python programs have to
>>> print(a) collect and process the data, store it, and use it. One of the most common
{'tomato, potato, garlic, ginger, pumpkin'} datatypes is known as strings. They appear to be simple at first glance,
however they can be used in several ways. A string is popularly written in the
>>> #This is python tuple form of characters. Anything that comes inside the quotation marks is dubbed
>>> a = ("tomato, potato, garlic, ginger, pumpkin") as a string. You can use single or double quotes to create a string. The
flexibility of using different types of quote marks is not without reason. It
>>> print(a)
serves several purposes. See that in the following code snippet.
tomato, potato, garlic, ginger, pumpkin
While single quotes allow you to write the code easily, double quotes allow
>>> #This is a dictionary you to use apostrophes in the text. In the following example, you will learn to
>>> a = {"fruit" : "tomato", "veg: potato", "veg" : "garlic", "veg" : "ginger", use both types of quotes and their dos and don’ts.
"veg" : "pumpkin"} >>> a = "I am learning Python."
SyntaxError: invalid syntax >>> print(a)
>>> a = {"fruit" : "tomato", "veg": "potato", "veg" : "garlic", "veg" : I am learning Python.
"ginger", "veg" : "pumpkin"}
>>> a = 'I am learning Python.'
>>> print(a)
>>> print(a)
{'fruit': 'tomato', 'veg': 'pumpkin'}
I am learning Python.
>>> a = {"fruit" : "tomato", "veg: potato", "veg1" : "garlic", "veg2" :
>>> a = "I am learning Tack's book on Python."
"ginger", "veg3" : "pumpkin"}
>>> print(a)
SyntaxError: invalid syntax
>>> a = {"fruit" : "tomato", "veg": "potato", "veg1" : "garlic", "veg2" : I am learning Tack's book on Python.
>>> a = 'I am learning Tacky's book on Python.' user like you entered the information in the capital case.
SyntaxError: invalid syntax Many Python programs invite data for storage purposes and then use it.
Sometimes you have two or more strings that you have to combine into one.
>>>
The process is known as string concatenation. For example, you can combine
Strings are very interesting if you get a full grasp of the concept. You can the name of the state and the country's name after you receive them
change the text into lower and upper texts. I will use the same string example independently. The odds are high that you invite the users' information
and experiment on it to see how we can change its case. separately because usually you have to create two columns on your interface
>>> a = "I am learning Python." to facilitate the users. When you receive them separately, you can combine
them with a simple method. See the following example.
>>> print([Link]())
>>> state_name = "california"
I Am Learning Python.
>>> country_name = "United States"
>>> print([Link]())
>>> Location_info = state_name + " " + country_name
I AM LEARNING PYTHON.
>>> print(Location_info)
>>> print([Link]())
california United States
i am learning python.
>>>
>>>
You can see that there is something wrong with the code. The display is
One of the easiest tasks is changing the case as you have seen. There are good, but it is not neat. We can add a comma to the code and see how we can
three keywords: upper, lower, and title cases to change any string you have use it. From here, I will shift from Python IDLE to Python text editor to give
created for your code. You can see in the code that all the three keywords are you a feel of how you will write a program. Let us see how to switch from
accompanied by () brackets. It is called a method. A method can be defined Python IDLE to the text editor.
as a kind of action that Python performs on a certain piece of data. Even a
character as little as a dot is meaningful in Python coding. The dot that comes The first step is to open Python IDLE or interpreter. Go to the File menu and
after the string's name directs Python to deploy the method, which can be the click New File. A new window will pop up on your computer screen. This is
title, lower, upper cases. Each method has parenthesis at the end to fill in a Python text editor. You can write the code on it. When you are done writing
additional information. I have left the parenthesis empty in the above- the code, you should click on Run on the top menu bar. The editor will ask
mentioned code because I did not have to fill it in with additional you to save the code first and then run it. You need to save the code to your
information. However, in the next few chapters, I will explain how you can desired location and Python will run your code. One important point to note
use the parenthesis to perform different types of tasks. They are quite is that when you run the code, a new window of Python IDLE will pop up to
interesting if you can use it in the right way. display the result of the code. In the next code samples, you will see the code
that is written in Python editor first, and attached to its tail will be the result
Out of all the methods, the lower() method is specifically used to store data in of the code. The second result will start from the word Restart. This is how
Python programs. You might have browsed a website that asked you to write you will easily learn it and practice it on your computer system. Let us jump
in small letters when you sought to enter some information on the database. to the Python editor now.
Still, you very possibly might have entered the information in a capital case.
The lower() method helps convert the strings into the lower case, even if a state_name = "California"
country_name = "United States" >>>
Location_info = state_name + " , " + country_name Let change the case of the strings and see how it works in the program.
print(Location_info) place_name = "Silicon Valley"
= RESTART: C:/Users/saifia computers/Desktop/[Link] state_name = "California"
California, United States country_name = "United States"
>>> location_info = place_name + " , " + state_name + " , " + country_name
This code is neat and clean as I have added a comma to it. The most print("Hi, I want to visit " + location_info.upper() + " in the next month.")
important thing to learn from this code sample is the plus operator used to
print("Hi, I want to visit " + location_info.lower() + " in the next month.")
combine the two strings. We can concatenate more than two strings as well. I
will now add the name of the place to the concatenated string. = RESTART: C:/Users/saifia computers/Desktop/[Link]
place_name = "Silicon Valley" Hi, I want to visit SILICON VALLEY, CALIFORNIA, UNITED STATES in
the next month.
state_name = "California"
Hi, I want to visit silicon valley, california, united states in the next month.
country_name = "United States"
>>>
location_info = place_name + " , " + state_name + " , " + country_name
You always have the option of creating a concatenated string and storing it in
print(location_info)
a variable so that you can use it later on as per your needs.
= RESTART: C:/Users/saifia computers/Desktop/[Link] place_name = "Silicon Valley"
Silicon Valley, California , United States
state_name = "California"
>>> country_name = "United States"
I will now use the same code to display a message to the user after he has
location_info = place_name + " , " + state_name + " , " + country_name
entered his location information.
info = "Hi, I want to visit " + location_info.title() + " in the next month."
place_name = "Silicon Valley"
print(info)
state_name = "California"
= RESTART: C:/Users/saifia computers/Desktop/[Link]
country_name = "United States"
Hi, I want to visit Silicon Valley , California , United States in the next
location_info = place_name + " , " + state_name + " , " + country_name month.
print("Hi, I want to visit " + location_info.title() + " in the next month.") >>>
= RESTART: C:/Users/saifia computers/Desktop/[Link] Python allows you to neatly format your strings by adding tabs, spaces and
Hi, I want to visit Silicon Valley, California, United States in the next month. other symbols.
place_name = "Silicon Valley" >>>
state_name = "California" Python Numbers
country_name = "United States" Numbers are more often used in programming to do calculations or store
data. For example, if you are developing a Python game, you need to keep the
location_info = place_name + " , " + state_name + " , " + country_name
scores calculated. Python integers are the simplest form of numbers that you
info = "\tHi, I want to visit " + location_info.title() + "\t in the next month." can use. I will do some calculations by using different mathematical
print(info) operators.
= RESTART: C:/Users/saifia computers/Desktop/[Link] a=3+6
Hi, I want to visit Silicon Valley , California , United States in the print(a)
next month. a = 10 - 5
>>> print(a)
The tab feature has worked perfectly. Now I will use the \n feature to start a=3*6
each word of the sentence on a new line.
print(a)
place_name = "Silicon Valley"
a = 18 / 6
state_name = "California"
print(a)
country_name = "United States"
a = 3 ** 6
location_info = place_name + " , " + state_name + " , " + country_name
print(a)
info = "\nHi, \nI \nwant \nto \nvisit " + location_info.title() + " \nin the \nnext
month." a = 15 ** 6

print(info) print(a)

= RESTART: C:/Users/saifia computers/Desktop/[Link] = RESTART: C:/Users/saifia computers/Desktop/[Link]

Hi, 9
5
I
want 18

to 3.0

visit Silicon Valley, California, United States 729

in the 11390625

next month. >>>


In the next example, I will use multiple operators to see how Python print(a)
maintains the order of mathematics.
a = 3.45 * 6.3 + 50.09 / 30.1
a = 3 + 6 * 18
print(a)
print(a)
a = 18.22 / 6.1 * 50.89
a = 10 - 5 + 45 print(a)
print(a) a = (3.21 * 6.23 )- 23.22
a = 3 * 6 + 50 / 30 print(a)
print(a)
a = (15.123 ** 6.23) + 100.456
a = 18 / 6 * 50
print(a)
print(a)
= RESTART: C:/Users/saifia computers/Desktop/[Link]
a = (3 * 6 )- 23 118.67649600000001
print(a) 49.76
a = (15 ** 6) + 100 23.399119601328902
print(a)
152.00259016393443
= RESTART: C:/Users/saifia computers/Desktop/[Link] -3.2216999999999985
111
22343252.55463075
50 >>>
19.666666666666668 When you mix up the datatypes without proper procedure, you get an error in
150.0 return. For example, you have to mix up date with day to display a string
-5 statement. This will trigger an error if you do not fill in the code with the
right datatype and through the right process.
11390725
place_name = "Silicon Valley"
>>>
state_name = "California"
The next number type is float. This is the decimal form of integer. See how to
country_name = "United States"
use them.
a = 3.0 + 6.344 * 18.234 location_info = place_name + " , " + state_name + " , " + country_name

print(a) date = 4

a = 10.1 - 5.56 + 45.22 info = "Hi, I want to visit " + location_info.title() + " in the next month on" +
date + " th." Chapter Three: Python Lists and Tuples
print(info)
= RESTART: C:/Users/saifia computers/Desktop/[Link] This chapter will walk you through the concept of Python lists. I will explain
what Python lists are and how you can use them in Python programs. Python
Traceback (most recent call last): lists are one of the most amazing features of Python programming. They
File "C:/Users/saifia computers/Desktop/[Link]", line 6, in <module> allow you to fill in loads of information in a succinct manner. They allow you
to pack up tons of information in an easy-to-access format. You can add
info = "Hi, I want to visit " + location_info.title() + " in the next month
millions of items to Python lists. Python lists are considered one of the robust
on" + date + " th."
features of Python programming.
TypeError: can only concatenate str (not "int") to str
A Python list is packed up with a streak of items that are adjusted in a
>>> specific order. A list can be filled with alphabets and digits. As a list may
The error is a type error. Python is unable to recognize the information you contain more than one element, the traditional naming practice for lists
have put in. In simple words, the wrong method to fill in the code has suggests that you give them a plural name. Let us assume that you are
confused Python. So, you have to turn the integer into a string first to display developing a game where a player has to set up an office with necessary
it in the right way. The technique is simple, but you will have to memorize it. items and sell the office to the highest bidder.

place_name = "Silicon Valley" officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table
lights']
state_name = "California"
print(officeitems)
country_name = "United States"
= RESTART: C:/Users/saifia computers/Desktop/[Link]
location_info = place_name + " , " + state_name + " , " + country_name
['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table lights']
date = 4
>>>
info = "Hi, I want to visit " + location_info.title() + " on the " + str(date) +
"the of July" The output is alright, except that you do not want your game users to see this
output. It should be in an easy-to-digest form. Rather than printing the
print(info) complete list, you can access certain elements in the list by a simple method.
= RESTART: C:/Users/saifia computers/Desktop/[Link] For example, the player in your game wants to see which item has been
included in the office set up. To see that he should be able to access different
Hi, I want to visit Silicon Valley, California, United States on the 4th of July items in the list. Here is the method you can include in your program to help
>>> your players confirm the inclusion of different items.
I have told python that I have to add an integer to the string statement. officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table
lights']
print(officeitems[0])
print(officeitems[2])
print(officeitems[4]) print(officeitems[1].upper())
print(officeitems[5]) print(officeitems[2].lower())
print(officeitems[6]) = RESTART: C:/Users/saifia computers/Desktop/[Link]
= RESTART: C:/Users/saifia computers/Desktop/[Link] Printer
printer SCANNER
fan fan
chair >>>
computer system One important point to note regarding lists is that the first item in the list
tends to start from zero. If you fill it in with 1, it means you are trying to
table lights
access the second item on the list. If you want to access the fifth item on the
>>> list, you will have to use index number 3. There is another way to access
When you are writing the code for your game, you may run into a serious items on the list. You can access the item by using negative indices. In the
problem. Your player may want to access the item no 10 in the list, which following example, I will access items both from positive and negative
does not exist in the first place as there are only seven items on the list. When indices.
the player tries to do that, the result will be an index error. officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table
officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table lights']
lights'] print(officeitems[0])
print(officeitems[10]) print(officeitems[1])
= RESTART: C:/Users/saifia computers/Desktop/[Link] print(officeitems[2])
Traceback (most recent call last): print(officeitems[-1])
File "C:/Users/saifia computers/Desktop/[Link]", line 2, in <module> print(officeitems[-2])
print(officeitems[10]) print(officeitems[-3])
IndexError: list index out of range = RESTART: C:/Users/saifia computers/Desktop/[Link]
>>> printer
You can deploy string methods to make the lists look neat and clean. I will scanner
use the title, lower and upper case methods to format the items from the list.
fan
officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table
lights'] table lights

print(officeitems[0].title()) computer system


chair officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table
lights']
>>>
comment = "Dear player! The " + officeitems[2].title() + " is operational."
While the positive index starts from the left side, the negative index starts
from the right side. It will pick the values from the end of the list and display print(comment)
them to the user. comment = "Dear player! The " + officeitems[0].title() + " is operational."
Let us make the game more interesting by adding statements and using items print(comment)
from the list to build those statements. Each time your player buys something
from the market and adds it to the office, he will receive a message on the comment = "Dear player! The " + officeitems[6].title() + " are operational."
screen that informs him how much he has achieved. I will use individual print(comment)
values from the list and apply the method of concatenation to create a
message. = RESTART: C:/Users/saifia computers/Desktop/[Link]
officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table Dear player! The Fan is operational.
lights'] Dear player! The Printer is operational.
comment = "Dear player! You have successfully purchased a " + Dear player! The Table Lights are operational.
officeitems[2].title() + "."
>>>
print(comment)
Modifying Lists
comment = "Dear player! You have successfully purchased a " +
officeitems[0].upper() + "." When you have created a list, you can easily change its items, add more items
to it, and remove certain items. In this sense, lists are very flexible. Most of
print(comment) the lists that you create are dynamic. You can offer your player a choice to
comment = "Dear player! You have successfully purchased a " + add different items to your list and remove items from the list of office items
officeitems[2].lower() + "." to increase or decrease the office's value. The faster he sells or the bigger he
sells matter for the overall gaming score of the player.
print(comment)
officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table
= RESTART: C:/Users/saifia computers/Desktop/[Link] lights']
Dear player! You have successfully purchased a Fan. print(officeitems)
Dear player! You have successfully purchased a PRINTER. # I will change the value of different items at different indices
Dear player! You have successfully purchased a fan. officeitems[0] = 'water dispenser'
>>> print(officeitems)
You can use the same items in different ways. All it needs a pinch of = RESTART: C:/Users/saifia computers/Desktop/[Link]
creativity. When the player has installed the items in the office, you can
display a message on the screen to show that the items are operational. ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table lights']
['water dispenser', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table lights', 'water
lights'] dispenser', 'multimedia projector', 'air conditioner']
>>> ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table lights', 'water
Append Method dispenser', 'multimedia projector', 'air conditioner', 'laptop']

In the first line, I have displayed the original list. In the next line of code, I >>>
will change the first item's value and redisplay the list. The player has The append method helps you build lists in perfect order. This is the most
successfully replaced the item to boost the sale value of the office. You also efficient way to build lists in a perfectly dynamic way. You can even start
can allow your player to keep adding more items to the office to beef up the appending elements to an empty list. This is how your player will have more
value. One of the easiest and the most amazing way to add items to a list is freedom to start right from scratch. He will see an empty office and equip it
by using the append method. This method is the simplest of adding new with the items he wants to add to it.
elements to a list. When you apply the append method, the element you want While the append method adds elements to the end of your lists, you can use
to add will be added to the end of the list. The player does not have a choice the insert method to add items to the position of your choice. The first you
to add it to his favorite index. need to do is to specify the index of each new element. See the following
officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table example.
lights'] officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table
print(officeitems) lights']
[Link]('water dispenser') print(officeitems)
print(officeitems) [Link](0, 'air conditioner')
[Link]('multimedia projector') print(officeitems)
print(officeitems) [Link](2, 'multimedia projector')
[Link]('air conditioner') print(officeitems)
print(officeitems) [Link](3, 'water dispenser')
[Link]('laptop') print(officeitems)
print(officeitems) = RESTART: C:/Users/saifia computers/Desktop/[Link]
= RESTART: C:/Users/saifia computers/Desktop/[Link] ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table lights']
['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table lights'] ['air conditioner', 'printer', 'scanner', 'fan', 'table', 'chair', 'computer system',
['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table lights', 'water 'table lights']
dispenser'] ['air conditioner', 'printer', 'multimedia projector', 'scanner', 'fan', 'table',
['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table lights', 'water 'chair', 'computer system', 'table lights']
dispenser', 'multimedia projector'] ['air conditioner', 'printer', 'multimedia projector', 'water dispenser', 'scanner',
'fan', 'table', 'chair', 'computer system', 'table lights'] can use the item later on. This is why the pop() method is different from the
>>> del() method. Imagine that the office items are stacked up one upon another
and you get the opportunity to pick and throw out from the top one by one.
Del Method This is how the pop() method works.
There may be occasions in the game when a player wants to remove certain I will use the pop() method until the list stands empty to show how a player
items from the office to adjust the office to his desires. You can easily can empty an office off the items if he wants to.
remove different items from a list by a simple method. The first method is
that of the del statement. Let us check how you can add this method to your officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table
code to make the game more interactive. lights']

officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table print(officeitems)
lights'] popped_officeitems = [Link]()
print(officeitems) print(officeitems)
del officeitems[0] print(popped_officeitems)
print(officeitems) popped_officeitems = [Link]()
del officeitems[1] print(officeitems)
print(officeitems) print(popped_officeitems)
del officeitems[2] popped_officeitems = [Link]()
print(officeitems) print(officeitems)
= RESTART: C:/Users/saifia computers/Desktop/[Link] print(popped_officeitems)
['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table lights'] popped_officeitems = [Link]()
['scanner', 'fan', 'table', 'chair', 'computer system', 'table lights'] print(officeitems)
['scanner', 'table', 'chair', 'computer system', 'table lights'] print(popped_officeitems)
['scanner', 'table', 'computer system', 'table lights'] popped_officeitems = [Link]()
>>> print(officeitems)
Pop Method print(popped_officeitems)
While the del method demands from you that you mention the index number, popped_officeitems = [Link]()
you always have the choice to use another method, the pop() method, to
print(officeitems)
remove items from your lists. This is helpful if you want to give your players
the freedom to randomly remove items from the office setup. print(popped_officeitems)
The pop() method tends to eject items from the end of the list. However, you popped_officeitems = [Link]()
print(officeitems) item from the item, you can add another line of code to your program.
print(popped_officeitems) officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table
lights']
= RESTART: C:/Users/saifia computers/Desktop/[Link]
print(officeitems)
['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table lights']
['printer', 'scanner', 'fan', 'table', 'chair', 'computer system'] popped_officeitems = [Link]()
print("I have sold " + popped_officeitems.title() + " because it was not adding
table lights
the desired value to the office.")
['printer', 'scanner', 'fan', 'table', 'chair']
= RESTART: C:/Users/saifia computers/Desktop/[Link]
computer system
['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table lights']
['printer', 'scanner', 'fan', 'table']
I have sold Table Lights because it was not adding the desired value to the
chair office.
['printer', 'scanner', 'fan'] >>>
table Unlike what most people think, the pop() method allows you to remove items
['printer', 'scanner'] from a list at specific positions of your choice. You have to fill in the
parenthesis with the desired index number.
fan
officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table
['printer'] lights']
scanner print(officeitems)
[] popped_officeitems = [Link](3)
printer print("I have sold the " + popped_officeitems.title() + " because it was not
>>> adding the desired value to the office.")
Once there are no more items in the list but you still use the pop() method, it = RESTART: C:/Users/saifia computers/Desktop/[Link]
will return an error that will look like the following. ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table lights']
Traceback (most recent call last): I have sold the Table because it was not adding the desired value to the
File "C:/Users/saifia computers/Desktop/[Link]", line 24, in <module> office.
popped_officeitems = [Link]() >>>
IndexError: pop from empty list Remove Method
In the following section, I will show you how you can use the popped item in Another method to remove items from a list by using the remove method.
the code. If you want your player to explain to his boss why he removed an Many times you do not know the specific position of a value that you want to
remove. In that case, you can remove the item by using the value of that item. >>>
To do that you have to fill in the parenthesis of the remove() method with the List Organization
value.
More often when you create lists, they flow in a kind of unpredictable order.
officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table You cannot always control the order in which the users provide data to the
lights'] program. However, you can bring that information into perfect order later on.
print(officeitems) It may happen more often than you want to make the information presentable.
This is the reason you should bring it into perfect order. There are several
[Link]('scanner')
ways by which you can order lists in Python.
print(officeitems)
The sort() Method
[Link]('table')
The sort method of Python makes it fun to sort a list. I will use the same list
print(officeitems) of officeitems and experiment on it to see how the list gets organized. The
= RESTART: C:/Users/saifia computers/Desktop/[Link] sort() method sorts lists in an alphabetical order.

['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table lights'] officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']

['printer', 'fan', 'table', 'chair', 'computer system', 'table lights'] print(officeitems)


['printer', 'fan', 'chair', 'computer system', 'table lights'] [Link]()
>>> print(officeitems)
Just like you used the popped value later on in the code, you can also use the = RESTART: C:/Users/saifia computers/Desktop/[Link]
removed value from the item. ['printer', 'scanner', 'fan', 'table', 'table lights']
officeitems = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table ['fan', 'printer', 'scanner', 'table', 'table lights']
lights']
>>>
print(officeitems)
The sort() method has changed the list into a perfect alphabetical order. You
removeditem = 'scanner' cannot revert to the original order once you have sorted your list. The sort()
[Link](removeditem) can also be used to order the list in the reverse alphabetical order.
print("I have sold the " + [Link]() + " because it was not adding officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
the desired value to the office.") print(officeitems)
= RESTART: C:/Users/saifia computers/Desktop/[Link] [Link](reverse=True)
['printer', 'scanner', 'fan', 'table', 'chair', 'computer system', 'table lights'] print(officeitems)
I have sold the Scanner because it was not adding the desired value to the = RESTART: C:/Users/saifia computers/Desktop/[Link]
office.
['printer', 'scanner', 'fan', 'table', 'table lights']
['table lights', 'table', 'scanner', 'printer', 'fan'] IndexError: list index out of range
>>> >>>
Coupled with the sort() method is the sorted() function. While the sort() The list contains five items, but when I invoke the index number 5, I get an
method permanently reorders a list, the sorted() function makes temporary error message. Just as for strings, the index for lists also starts at zero.
changes. Index errors come up more often if the list is a long one. The best practice to
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights'] work with long lists is to know the exact length of the list. Once you know
print(officeitems) the length, you can sort out each item's index number in the list. See the
following method to check the length of the list.
print(sorted(officeitems))
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
print(officeitems)
len(officeitems)
= RESTART: C:/Users/saifia computers/Desktop/[Link]
Create A Loop
['printer', 'scanner', 'fan', 'table', 'table lights']
Python lists can be operated with loops. Coming back to the game. If you
['fan', 'printer', 'scanner', 'table', 'table lights'] want your player to have the option of displaying all the items that he has set
['printer', 'scanner', 'fan', 'table', 'table lights'] up in his office, you can run a loop through your list. This is helpful if you
have added another character to your game who asks the player about the
>>> total number of items that he has bought for the office. Each item in the list
You can see that the sorted() function temporarily changed the order of the will be neatly displayed. The for loop in Python will repeat the same action
list. When I printed the list without the sorted() function, it comes back into with each item.
its original order. I will use the same list of office items and print each item by looping the list
Index Errors with a for loop. Let us now create and build a for loop to print out each item
you have bought for the office.
As errors are common in coding, you may run into index errors in lists. One
of the most common types of errors with lists is the index error. You may officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
confront this type of error more often when you work on lists. However, you for officeitem in officeitems:
can easily avoid that if you know at which point the index starts. Let us see
first how the error message looks like. print(officeitem)

officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights'] = RESTART: C:/Users/saifia computers/Desktop/[Link]
print(officeitems[5]) printer
= RESTART: C:/Users/saifia computers/Desktop/[Link] scanner
Traceback (most recent call last): fan
File "C:/Users/saifia computers/Desktop/[Link]", line 2, in <module> table
print(officeitems[5]) table lights
>>> printer
Python for loop has looped through and printed each item on the list. When scanner
you are writing this code, you may hit an error which can be hard to explain
fan
because there will be no exact error message on the interpreter screen. See the
following example. table
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights'] table lights
for officeitem in officeitems: >>>
print(officeitems) Looping is an important concept in computer programming because it is used
to automate some recitative tasks. If your list is packed up with a million
= RESTART: C:/Users/saifia computers/Desktop/[Link] items, Python loops will repeat the steps a million times and in a very fast
['printer', 'scanner', 'fan', 'table', 'table lights'] manner.
['printer', 'scanner', 'fan', 'table', 'table lights'] The Python for loop is amazing because it allows you to experiment with the
['printer', 'scanner', 'fan', 'table', 'table lights'] office items quickly. You have to set the code right and the entire list will be
fully automated. I will now take each item from the list and display a
['printer', 'scanner', 'fan', 'table', 'table lights'] message on the Python interpreter screen. If you want your player to tell his
['printer', 'scanner', 'fan', 'table', 'table lights'] boss he has purchased each item at a discount price and from a quality
production house, you can slightly change the code and display the message
>>> most uniquely.
All I did was to add an s to officeitem in the last line of code. Python officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
interpreted it differently and looped through the entire list and displayed it
repetitively. Instead of getting an error message, Python changes the results. for officeitem in officeitems:
What exactly I did in the code. In the first line of code, I have defined a list, print("I have purchased the " + [Link]() + " at a discount price
namely officeitems. In the next line, I have defined a for loop. This line from TopQuality Productions.")
instructs Python to pick a name from the list and store it in the newly created = RESTART: C:/Users/saifia computers/Desktop/[Link]
variable officeitem. It is not necessary to name a variable in this way, but it is
easy to remember. You can name it as you like. In the next line, I told Python I have purchased the printer at a discount price from TopQuality Productions.
to print each name that I had stored in the new variable. Python repeats lines I have purchased the scanner at a discount price from TopQuality
for each item in the list. To kill the confusion about the name of the variable, Productions.
I will now change the variable's name.
I have purchased the fan at a discount price from TopQuality Productions.
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights'] I have purchased the table at a discount price from TopQuality Productions.
for things in officeitems:
I have purchased the table lights at a discount price from TopQuality
print(things) Productions.
= RESTART: C:/Users/saifia computers/Desktop/[Link] >>>
So, this is getting interesting now. This is how you can develop your game in officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
a brilliantly interactive manner. If you want the player to speak more than one
for officeitem in officeitems:
line, you can pair up more sentences to the reply. Each line will be executed
in the order you write it in the code. I will now add a second line of code to print("I have purchased the " + [Link]() + " at a discount price
the response of the player. from TopQuality Productions.")
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights'] print ("I hope the " + [Link]() + " will add more value to the
office.")
for officeitem in officeitems:
print("Thanks for making the purchase. Hope you will be able to sell out the
print("I have purchased the " + [Link]() + " at a discount price office this month. After all, you won't like to be deprived of your bonus.")
from TopQuality Productions.")
= RESTART: C:/Users/saifia computers/Desktop/[Link]
print ("I hope the " + [Link]() + " will add more value to the
office.") I have purchased the printer at a discount price from TopQuality Productions.
= RESTART: C:/Users/saifia computers/Desktop/[Link] I hope the printer will add more value to the office.
I have purchased the printer at a discount price from TopQuality Productions. I have purchased the scanner at a discount price from TopQuality
Productions.
I hope the printer will add more value to the office.
I hope the scanner will add more value to the office.
I have purchased the scanner at a discount price from TopQuality
Productions. I have purchased the fan at a discount price from TopQuality Productions.
I hope the scanner will add more value to the office. I hope the fan will add more value to the office.
I have purchased the fan at a discount price from TopQuality Productions. I have purchased the table at a discount price from TopQuality Productions.
I hope the fan will add more value to the office. I hope the table will add more value to the office.
I have purchased the table at a discount price from TopQuality Productions. I have purchased the table lights at a discount price from TopQuality
Productions.
I hope the table will add more value to the office.
I hope the table lights will add more value to the office.
I have purchased the table lights at a discount price from TopQuality
Productions. Thanks for making the purchase. Hope you will be able to sell out the office
this month. After all, you won't like to be deprived of your bonus.
I hope the table lights will add more value to the office.
>>>
>>>
All I did was to remove the space before the print statement by which I want
This is how you can add a hundred lines if your program or game requires to end the for loop. This explains how crucial a role spaces play in Python
that. You also can add a finishing note to the end of a block of code. The
programming. You miss out on an indentation and you will see an error on
finishing block of code executes without repetition. I will now add a reply the screen.
from the boss in the game who has heard what the player said about
purchasing items. officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
for officeitem in officeitems: officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
print(officeitem) print(officeitems[-2:])
Expected an indented block = RESTART: C:/Users/saifia computers/Desktop/[Link]
List Slicing ['table', 'table lights']
You can slice a list to work with a portion of a list. This is helpful if you are >>>
building a long list of items and you have to work only with a handful of You also can loop through the subset of a list or the slice of a list just like we
items. I will use the same list for slicing.
did with a complete list.
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights'] officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
print(officeitems[1:4]) print("Here are the items that have cost double the value of others.")
= RESTART: C:/Users/saifia computers/Desktop/[Link] for officeitem in officeitems[:4]:
['scanner', 'fan', 'table'] print([Link]())
>>> = RESTART: C:/Users/saifia computers/Desktop/[Link]
The result contains only the items that I have sliced out of the original list.
Here are the items that have cost double the value of others.
The output comes in the form of the original structure of the list. The sliced
part of the list can also be named as a subset of the list. If you omit the Printer
index's start, the subset of the list will start from the first item. Scanner
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights'] Fan
print(officeitems[:4]) Table
= RESTART: C:/Users/saifia computers/Desktop/[Link] >>>
['printer', 'scanner', 'fan', 'table'] Copying
>>> You can create a copy of the list based on the original list. This is helpful if
Similarly, you can omit the second half of the range index. you have packed up customer data in a list and you want to save it elsewhere
to secure it in the wake of data breaches or any other kind of cyberattack. The
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights'] most common way of making a copy of the list is to create a slice with no
print(officeitems[2:]) starting or ending values. This slice instructs Python to slice the list right
= RESTART: C:/Users/saifia computers/Desktop/[Link] from the starting value to the ending value. This is how you end up creating a
copy of your list.
['fan', 'table', 'table lights']
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
>>>
c_officeitems = officeitems[:]
The negative indexing is also available for Python lists.
print("Here is the list of items that I have purchased.") You can see that the two lists exist independently and that you can modify
them separately. This is helpful if you are building data lists for a big
print(officeitems)
financial institution.
print("\nHere is the exact copy of the same items.")
You may create a copy of the list without using the slice method but you will
print(c_officeitems) not be able to modify the two lists independently of each other. They will not
= RESTART: C:/Users/saifia computers/Desktop/[Link] be able to exist independently of each other.
Here is the list of items that I have purchased. officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
['printer', 'scanner', 'fan', 'table', 'table lights'] c_officeitems = officeitems
Here is the exact copy of the same items. [Link]('computer system')

['printer', 'scanner', 'fan', 'table', 'table lights'] c_officeitems.append('blinds')

>>> print("Here is the list of items that I have purchased.")


Let us now check if you really have two lists and that if removing or print(officeitems)
modifying one list will affect the copied list or not. print("\nHere is the new list of office items.")
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights'] print(c_officeitems)
c_officeitems = officeitems[:] = RESTART: C:/Users/saifia computers/Desktop/[Link]
[Link]('computer system') Here is the list of items that I have purchased.
c_officeitems.append('blinds') ['printer', 'scanner', 'fan', 'table', 'table lights', 'computer system', 'blinds']
print("Here is the list of items that I have purchased.") Here is the new list of office items.
print(officeitems) ['printer', 'scanner', 'fan', 'table', 'table lights', 'computer system', 'blinds']
print("\nHere is the new list of office items.") >>>
print(c_officeitems) You can see that each list retained both newly added items. I will now add
= RESTART: C:/Users/saifia computers/Desktop/[Link] one item to one list only and see if the copied list retains that item or not.
Here is the list of items that I have purchased. officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']

['printer', 'scanner', 'fan', 'table', 'table lights', 'computer system'] c_officeitems = officeitems

Here is the new list of office items. [Link]('computer system')


['printer', 'scanner', 'fan', 'table', 'table lights', 'blinds']
print("Here is the list of items that I have purchased.")
>>>
print(officeitems)
print("\nHere is the new list of office items.") ('dining table', 'cooking range', 'washing machine', 'refrigerator', 'air
conditioner')
print(c_officeitems)
>>>
= RESTART: C:/Users/saifia computers/Desktop/[Link]
Let us see what happens when we try to change the value of an item in the
Here is the list of items that I have purchased.
tuple.
['printer', 'scanner', 'fan', 'table', 'table lights', 'computer system']
homeitems = ('dining table', 'cooking range', 'washing machine', 'refrigerator',
Here is the new list of office items. 'air conditioner')
['printer', 'scanner', 'fan', 'table', 'table lights', 'computer system'] homeitems[0] = ('bed')
>>> print(homeitems)
So, as you can see that simply copying a list will not do the magic for you. = RESTART: C:/Users/saifia computers/Desktop/[Link]
Slicing helps you make the copy you desire for.
Traceback (most recent call last):
Python Tuples
File "C:/Users/saifia computers/Desktop/[Link]", line 2, in <module>
While lists can be modified and are flexible, Python tuples are the opposite.
Once you have created a tuple, you cannot change it. A tuple is similar to a homeitems[0] = ('bed')
list in the sense that you can fill it up with millions of items but at the same TypeError: 'tuple' object does not support item assignment
time, it is different from a list in the sense that you cannot add, remove or >>>
change the items in a tuple. This is helpful if you want to create a list that you
do not want to be changed. The values in a tuple that cannot be changed are You see an error because Python does not allow you to modify tuples.
labeled as immutable in Python. So, you can label a rigid list or a tuple as an However, there is a way out by which you modify a tuple. You can do the
immutable list. modification by assigning new values to the same variable that carries the
tuple. In the following code snippet, I will redefine the tuple.
In appearance, a tuple looks mostly like a list except that you have to enclose
the tuple items inside square brackets. Once you have created a tuple, you can homeitems = ('dining table', 'cooking range', 'washing machine', 'refrigerator',
easily access the tuples' items by using the index number. I will add a new 'air conditioner')
feature to the game by creating a list of home items that the same player print("Original items in the tuple:")
needs to sell. The difference is that the player cannot change the items of the
house except in exceptional circumstances. He has to sell the house the way it for homeitem in homeitems:
is at the moment. He cannot add more items or remove the existing ones to print(homeitem)
tune the house's value as per the expectations and demands of buyers.
homeitems = ('chairs', 'carpets', 'plates', 'oven')
homeitems = ('dining table', 'cooking range', 'washing machine', 'refrigerator',
print("Modified items in the tuple:")
'air conditioner')
print(homeitems) for homeitem in homeitems:

= RESTART: C:/Users/saifia computers/Desktop/[Link] print(homeitem)


= RESTART: C:/Users/saifia computers/Desktop/[Link] >>>
Original items in the tuple:
dining table
cooking range
washing machine
refrigerator
air conditioner
Modified items in the tuple:
chairs
carpets
plates
oven
>>>
Tuples are data structures that can be used to store values that cannot be
changed through a program.
Looping
Just like lists, you can create a loop through your tuple.
homeitems = ('dining table', 'cooking range', 'washing machine', 'refrigerator',
'air conditioner')
for homeitem in homeitems:
print(homeitem)
= RESTART: C:/Users/saifia computers/Desktop/[Link]
dining table
cooking range
washing machine
refrigerator
air conditioner
Chapter Four: Python Conditionals list. You also can use the item to display a message or comment.
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
A key part of programming is about examining a set of conditions and then item = 'scanner'
taking appropriate action based on the conditions. The if statement in Python
lets you test the state of a program and act on it appropriately. This chapter item1 = 'table'
will walk you through the process of writing conditionals and checking them item2 = 'extension cable'
as well. The chapter will encompass simple and complex if statements. I will
if item in officeitems:
explain how you can pair up an if statement with lists.
print([Link]() + " exists in the office.")
homeitems = ['dining table', 'cooking range', 'washing machine', 'refrigerator',
'air conditioner'] if item1 in officeitems:
for homeitem in homeitems: print([Link]() + " exists in the office.")
if homeitem == 'dining table': if item2 not in officeitems:
print([Link]()) print([Link]() + " is not exist in the office. You should buy it as soon
as possible.")
else:
= RESTART: C:/Users/saifia computers/Desktop/[Link]
print([Link]())
Scanner exists in the office.
= RESTART: C:/Users/saifia computers/Desktop/[Link]
Table exists in the office.
DINING TABLE
Extension Cable does not exist in the office. You should buy it as soon as
Cooking Range
possible.
Washing Machine
>>>
Refrigerator
Let us see what more you can do with the conditional statements. You can
Air Conditioner add the conditional statement to tell the player when the office will be ready
>>> for listing in the game.

The simplest conditional test tends to check if a particular variable's value officeitems = 10
stands equal to your value of interest. Sometimes you need to check if a value if officeitems >= 10:
exists in a list or not. The player in the game might want to check if a certain
print("You can list the office for sale")
item has been purchased or not before he lists the office for sale.
= RESTART: C:/Users/saifia computers/Desktop/[Link]
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
You can list the office for sale
'scanner' in officeitems
>>>
You can use the conditional statements to check if a certain item appears in a
See the following example with an additional print statement. officeitems = 9
officeitems = 12 if officeitems >= 10:
if officeitems >= 10: print("You can list the office for sale")
print("You can list the office for sale") print("Have you listed it yet?")
print("Have you listed it yet.") else:
= RESTART: C:/Users/saifia computers/Desktop/[Link] print("Sorry, you cannot list the office for sale.")
You can list the office for sale print("Please buy and add more items to the office and list it again for
sale.")
Have you listed it yet?
= RESTART: C:/Users/saifia computers/Desktop/[Link]
>>>
Sorry, you cannot list the office for sale.
The if-else Statement
The condition can be interesting if you add to it the else statement to print a Please buy and add more items to the office and list it again for sale.
statement if the count of items has not matured yet. The if-else statement >>>
allows you to test the conditions in both ways. The else statement defines an
The if-elif-else Chain
action when a particular condition fails.
The elif statement allows you to add one more condition to the block of code.
officeitems = 11
officeitems = 5
if officeitems >= 10:
if officeitems < 10:
print("You can list the office for sale")
print("You still can list the office but it will not bring you the desired
print("Have you listed it yet?") amount of money.")
else:
elif officeitems < 15:
print("Sorry, you cannot list the office for sale.") print("You can list the office for sale")
print("Please buy and add more items to the office and list it again for print("Have you listed it yet?")
sale.")
= RESTART: C:/Users/saifia computers/Desktop/[Link] else:
You can list the office for sale print("Sorry, you cannot list the office for sale.")
Have you listed it yet? print("Please buy and add more items to the office and list it again for
>>> sale.")
As the items are more than 10, the condition has been tested passed. Now I = RESTART: C:/Users/saifia computers/Desktop/[Link]
will reduce the count of the items to test the else-statement.
You still can list the office, but it will not bring you the desired amount of = RESTART: C:/Users/saifia computers/Desktop/[Link]
money.
I have purchased the printer.
>>>
I have purchased the fan.
You can test multiple conditions with conditional statements.
I have purchased the scanner.
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights'] You can list the office now.
if 'printer' in officeitems: >>>
print("I have purchased the printer.") The same code cannot work with an elif statement. It will stop working. See
if 'fan' in officeitems: what happens when we remove the simple if statement and add an elif
print("I have purchased the fan.") statement.

if 'scanner' in officeitems: officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']

print("I have purchased the scanner.") if 'printer' in officeitems:

= RESTART: C:/Users/saifia computers/Desktop/[Link] print("I have purchased the printer.")


elif 'fan' in officeitems:
I have purchased the printer.
I have purchased the fan. print("I have purchased the fan.")

I have purchased the scanner. elif 'scanner' in officeitems:

>>> print("I have purchased the scanner.")

When the player has checked if he has purchased all the desired items, the print("\nYou can list the office now.")
game will give him a green signal to list the office. You can add a print = RESTART: C:/Users/saifia computers/Desktop/[Link]
statement at the end of the block of code.
I have purchased the printer.
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights'] You can list the office now.
if 'printer' in officeitems: >>>
print("I have purchased the printer.") If Statements and Lists
if 'fan' in officeitems: You can pair up if statements with lists. You can actually combine the two
print("I have purchased the fan.") and do some amazing things. In the next example, I will pair up a loop with a
if 'scanner' in officeitems: list to make the game more interactive.

print("I have purchased the scanner.") officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']

print("\nYou can list the office now.") for officeitem in officeitems:


print("I have purchased the " + officeitem + ".") However, I have purchased the table.
print("\nBoss: You can list the office for sale now.") However, I have purchased the table lights.
= RESTART: C:/Users/saifia computers/Desktop/[Link] Boss: You can list the office for sale only after purchasing the cupboard and
setting it up in the office.
I have purchased the printer.
I have purchased the scanner. >>>

I have purchased the fan. Now, the Python interpreter checks each office item before it displays the
message. The code confirms if the boss has asked for the cupboard. When he
I have purchased the table. asks for the item, he gets a different response from the employee. The else
I have purchased the table lights. block makes sure that the response is in affirmative for all the other items.

Boss: You can list the office for sale now. Multiple Lists

>>> Up till now, we have worked with a single list. In this code sample, I will
work on multiple lists. I will add a list of optional items that may or may not
You have a straightforward result because the code contains a simple for be purchased. However, purchasing these items will help increase the value
loop. However, you can add a bit more complexity to the code. The boss may of the office.
ask the employee about a certain item that must be included in the office set
up before the office is put on sale. The employee has to handle the situation officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
in the most appropriate way. I will add an if-else statement along with the for optionalitems = ['pen', 'paper', 'drafting pads', 'books', 'water dispenser']
loop to make the code more flexible.
for optionalitem in optionalitems:
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
if optionalitem in officeitems:
for officeitem in officeitems:
print("The office has been set up will all the essential and optional
if officeitem == 'cupboard': items.")
print("Sorry Boss, I have not purchased it yet.") else:
else: print("Sorry, I have not purchased the " + optionalitem + ".")
print("However, I have purchased the " + officeitem + ".") print("\nBoss: You can list the office for sale only after you purchase the
print("\nBoss: You can list the office for sale only after you purchase the optional items and set them up in the office.")
cupboard and set it up in the office.") = RESTART: C:/Users/saifia computers/Desktop/[Link]
= RESTART: C:/Users/saifia computers/Desktop/[Link] Sorry, I have not purchased the pen.
However, I have purchased the printer. Sorry, I have not purchased the paper.
However, I have purchased the scanner. Sorry, I have not purchased the drafting pads.
However, I have purchased the fan. Sorry, I have not purchased the books.
Sorry, I have not purchased the water dispenser. >>>
Boss: You can list the office for sale only after purchasing the optional items
and setting them up in the office.
>>>
I defined the list of office items and optional items. I created a loop through
the optional items to check if they also are added to the office or not. Upon
the checking of each item, a message is displayed. In the end, the boss gives
his verdict on whether to list the office or not. In the code mentioned above,
the office does not contain any item from the list of optional items, therefore
it displayed the same message. You can change that by including one or two
optional items in the list of office items. See the following code.
officeitems = ['printer', 'paper', 'drafting pads', 'scanner', 'fan', 'table', 'table
lights']
optionalitems = ['pen', 'paper', 'drafting pads', 'books', 'water dispenser']
for optionalitem in optionalitems:
if optionalitem in officeitems:
print("I have purchased the " + optionalitem + ".")
else:
print("Sorry, I have not purchased the " + optionalitem + ".")
print("\nBoss: You can list the office for sale only after you purchase all the
optional items and set them up in the office.")
= RESTART: C:/Users/saifia computers/Desktop/[Link]
Sorry, I have not purchased the pen.
I have purchased the paper.
I have purchased the drafting pads.
Sorry, I have not purchased the books.
Sorry, I have not purchased the water dispenser.
Boss: You can list the office for sale only after purchasing all the optional
items and setting them up in the office.
Chapter Five: Python Dictionaries = RESTART: C:/Users/saifia computers/Desktop/[Link]
HP
This chapter will walk you through the concept of Python dictionaries, which A4
are the most important part of Python coding. You can store information in a
dictionary in the form of pairs. You can easily access the information, modify LED
it, and delete it at will. Dictionaries are amazing in the sense that they allow wood
you to store unlimited information. Just like lists, I will explain how you can
blank
pair up a dictionary with a loop.
>>>
When you have a good grasp of Python dictionaries, you will learn how to
model an object with a dictionary's help. Creating a dictionary is simple, but Dictionaries are more complex than lists, therefore you need more
updating it and using it in a code can be tricky. I will move through this programming practice to handle them. You can see that a dictionary contains
chapter step by step. In the first code sample, I will create a simple key-value pairs where each key is automatically connected to its value. Each
dictionary. key's value can be a string or an integer or even a list in some cases. It also
can be a dictionary in a more complex code form. You have to wrap up a
officeitems = {'printer' : 'HP', 'paper': 'A4', 'drafting pads': 'blank', 'scanner':
dictionary in curly braces or the dictionary will display an error. A key has
'hybrid', 'table': 'wood', 'table lights': 'LED'}
directed association with its value.
print(officeitems)
Accessing values from a dictionary is easy. As you have seen in the above
= RESTART: C:/Users/saifia computers/Desktop/[Link] code sample, I tried to access each value with the help of a key or a
{'printer': 'HP', 'paper': 'A4', 'drafting pads': 'blank', 'scanner': 'hybrid', 'table': dictionary. Dictionaries are also very dynamic, and they allow you to add as
'wood', 'table lights': 'LED'} many key-value pairs to the dictionary as you desire. I will now take an
empty dictionary and fill it up with key-value pairs of my choice.
>>>
officeitems = {}
There is another way to access and display selected information from a
dictionary. You can use one of the pairs' values and use them to access the officeitems['printer'] = 'HP'
other value of the pair. See the following code example. officeitems['paper'] = 'A4'
officeitems = {'printer' : 'HP', 'paper': 'A4', 'drafting pads': 'blank', 'scanner': officeitems['drafting pads'] = 'blank'
'hybrid', 'table': 'wood', 'table lights': 'LED'}
officeitems['scanner'] = 'hybrid'
print(officeitems['printer'])
officeitems['table lights'] = 'LED'
print(officeitems['paper'])
print(officeitems)
print(officeitems['table lights'])
= RESTART: C:/Users/saifia computers/Desktop/[Link]
print(officeitems['table'])
{'printer': 'HP', 'paper': 'A4', 'drafting pads': 'blank', 'scanner': 'hybrid', 'table
print(officeitems['drafting pads']) lights': 'LED'}
>>> print(officeitems)
You also can modify the value of a key as you deem fit. In order to do that, del officeitems['table']
you have to mention the name of the dictionary and write the key in square
print(officeitems)
brackets. Then you have to write the new value for the same key.
del officeitems['table lights']
officeitems = {'printer' : 'HP', 'paper': 'A4', 'drafting pads': 'blank', 'scanner':
'hybrid', 'table': 'wood', 'table lights': 'LED'} print(officeitems)
print("I have purchased a printer by " + officeitems['printer'] + ".") = RESTART: C:/Users/saifia computers/Desktop/[Link]
officeitems['printer'] = 'dell' {'printer': 'HP', 'paper': 'A4', 'drafting pads': 'blank', 'scanner': 'hybrid', 'table':
'wood', 'table lights': 'LED'}
print("However, I have also purchased one more now by " +
officeitems['printer'] + ".") {'paper': 'A4', 'drafting pads': 'blank', 'scanner': 'hybrid', 'table': 'wood', 'table
lights': 'LED'}
= RESTART: C:/Users/saifia computers/Desktop/[Link]
{'drafting pads': 'blank', 'scanner': 'hybrid', 'table': 'wood', 'table lights': 'LED'}
I have purchased a printer by HP.
{'scanner': 'hybrid', 'table': 'wood', 'table lights': 'LED'}
However, I have also purchased one more now by dell.
{'table': 'wood', 'table lights': 'LED'}
>>>
{'table lights': 'LED'}
Removing Pairs
{}
When you don’t need a certain key-value pair, you can remove it easily. You
can apply the del statement to remove the key-value pair. All you have to do >>>
is to mention the name of your dictionary and key. I will remove different You can see that when all the pairs are removed, the result is an empty
items from the dictionary I have created earlier on. dictionary. One important thing to keep in mind is that the del statement
officeitems = {'printer' : 'HP', 'paper': 'A4', 'drafting pads': 'blank', 'scanner': removes a pair completely from the dictionary. Therefore, only use the del
'hybrid', 'table': 'wood', 'table lights': 'LED'} statement when you are sure that you do not need a certain key-value pair.
print(officeitems) A dictionary allows you to use the values in a print statement to display
certain messages.
del officeitems['printer']
officeitems = {'printer' : 'HP', 'paper': 'A4', 'drafting pads': 'blank', 'scanner':
print(officeitems)
'hybrid', 'table': 'wood', 'table lights': 'LED'}
del officeitems['paper'] print("I bought a printer by " + officeitems['printer'] + ".")
print(officeitems) print("I also bought a scanner by " + officeitems['scanner'] + ".")
del officeitems['drafting pads'] print("The paper if of the size " + officeitems['paper'] + ".")
print(officeitems)
print("The drafting pads are " + officeitems['drafting pads'] + ".")
del officeitems['scanner']
= RESTART: C:/Users/saifia computers/Desktop/[Link] The Key: scanner
I bought a printer by HP. The Value: hybrid
I also bought a scanner by hybrid. The Key: table
The paper if of the size A4. The Value: wood
The drafting pads are blank. The Key: table lights
>>> The Value: LED
I have used the print keyword in the code. Then I added the appropriate >>>
statement to the code. After that came the part of the concatenation operator.
There is another method to display the values of each key-value pair. See the
This is how you can use the values of a dictionary to display messages in following example.
your code.
officeitems = {'printer' : 'HP', 'paper': 'A4', 'drafting pads': 'blank', 'scanner':
Looping 'hybrid', 'table': 'wood', 'table lights': 'LED'}
Just like we formed a loop through a list, we can form the same through a for k, v in [Link]():
dictionary as well. A Python dictionary may contain a few millions of key-
value pairs. As a dictionary carries big amounts of data, Python allows you to print("\nThe Key: " + k)
create a loop through it to easily see each key-value pair and use it in a print("The Value: " + v)
program. In the first example, I will loop through each item in your
dictionary. = RESTART: C:/Users/saifia computers/Desktop/[Link]
officeitems = {'printer' : 'HP', 'paper': 'A4', 'drafting pads': 'blank', 'scanner': The Key: printer
'hybrid', 'table': 'wood', 'table lights': 'LED'} The Value: HP
for key, value in [Link](): The Key: paper
print("\nThe Key: " + key) The Value: A4
print("The Value: " + value) The Key: drafting pads
= RESTART: C:/Users/saifia computers/Desktop/[Link] The Value: blank
The Key: printer The Key: scanner
The Value: HP The Value: hybrid
The Key: paper The Key: table
The Value: A4 The Value: wood
The Key: drafting pads The Key: table lights
The Value: blank The Value: LED
>>> for items in [Link]():
One important thing to consider before moving on is the order in which print([Link]())
Python stores the key-value pairs. When you create and run a loop through a
dictionary, Python does not care about the order in which you had created the = RESTART: C:/Users/saifia computers/Desktop/[Link]
dictionary. It only tracks down the keys and their respective values.
Printer
officeitems = {'printer' : 'Produced by HP', 'paper': 'A4 type', 'drafting pads':
'It is blank', 'scanner': 'it is hybrid', 'table': 'made of wood', 'table lights': 'They Paper
are LED'} Drafting Pads
for items, features in [Link](): Scanner
print([Link]() + " carries the following feature: " + [Link]()) Table
Table Lights
= RESTART: C:/Users/saifia computers/Desktop/[Link]
>>>
Printer carries the following feature: Produced By Hp
Now I will form a loop through each key's values and display the result in the
Paper carries the following feature: A4 Type interpreter.
Drafting Pads carries the following feature: It Is Blank officeitems = {'printer' : 'Produced by HP', 'paper': 'A4 type', 'drafting pads':
Scanner carries the following feature: It Is Hybrid 'It is blank', 'scanner': 'it is hybrid', 'table': 'made of wood', 'table lights': 'They
are LED'}
Table carries the following feature: Made Of Wood
for items in [Link]():
Table Lights carries the following feature: They Are Led
print([Link]())
>>>
= RESTART: C:/Users/saifia computers/Desktop/[Link]
The code instructs Python to loop through the key-value pairs inside of the
dictionary. As the code loops through each pair, Python first stores each key Produced By Hp
inside the variable named items. It stores each value inside the variable A4 Type
named features. The same variables are then added to the print statement that
runs and displays related messages. It Is Blank
You can opt for looping through all the keys or values separately. For It Is Hybrid
example, sometimes you need to work just with the keys and only want to Made Of Wood
display them. There is a way out. See the following example.
They Are Led
officeitems = {'printer' : 'Produced by HP', 'paper': 'A4 type', 'drafting pads':
'It is blank', 'scanner': 'it is hybrid', 'table': 'made of wood', 'table lights': 'They >>>
are LED'} The sorted() Method
To make your loops more interesting, you can add to them the sorted() then cram them all inside a list.
method. A dictionary is not in order, therefore you need to bring it up in the
officeitem1 = {'printer' : 'Produced by HP', 'scanner': 'it is hybrid', 'laptop':
order you want it to be. You can use the sorted() method to make that happen.
'dell'}
officeitems = {'printer' : 'Produced by HP', 'paper': 'A4 type', 'drafting pads':
officeitem2 = {'paper': 'A4 type', 'drafting pads': 'It is blank', 'pen': 'parker'}
'It is blank', 'scanner': 'it is hybrid', 'table': 'made of wood', 'table lights': 'They
are LED'} officeitem3 = {'table': 'made of wood', 'table lights': 'They are LED', 'office
chair': 'boss'}
for items in sorted([Link]()):
officeitems = [officeitem1, officeitem2, officeitem3]
print([Link]() + " has been purchased at a discount price. I hope it will
help earn a handsome amount from the sale of the office") for officeitem in officeitems:
= RESTART: C:/Users/saifia computers/Desktop/[Link] print(officeitem)
Drafting Pads has been purchased at a discount price. I hope it will help earn
a handsome amount from the sale of the office = RESTART: C:/Users/saifia computers/Desktop/[Link]

Paper has been purchased at a discount price. I hope it will help earn a {'printer': 'Produced by HP', 'scanner': 'it is hybrid', 'laptop': 'dell'}
handsome amount from the sale of the office {'paper': 'A4 type', 'drafting pads': 'It is blank', 'pen': 'parker'}
Printer has been purchased at a discount price. I hope it will help earn a {'table': 'made of wood', 'table lights': 'They are LED', 'office chair': 'boss'}
handsome amount from the sale of the office
>>>
Scanner has been purchased at a discount price. I hope it will help earn a
The three dictionaries denote each section of the office items. One deals with
handsome amount from the sale of the office
IT set up, the second denotes stationary while the third section denotes office
Table has been purchased at a discount price. I hope it will help earn a furniture.
handsome amount from the sale of the office
Random Dictionary Methods
Table Lights have been purchased at a discount price. I hope it will help earn
Dictionaries are flexible in the sense that they allow you to do several things.
a handsome amount from the sale of the office
For example, you can check if a certain key exists in the dictionary or not. I
>>> will use the if statement in the code.
You can see that the result is in perfect alphabetical order. officeitem1 = {'printer' : 'Produced by HP', 'scanner': 'it is hybrid', 'laptop':
Nesting 'dell', 'paper': 'A4 type', 'drafting pads': 'It is blank', 'pen': 'parker', 'table':
'made of wood', 'table lights': 'They are LED', 'office chair': 'boss'}
Ever wondered if you can make a dictionary more complex than it already is.
You can nest a long dictionary inside another dictionary. The process is if "scanner" in officeitem1:
dubbed as nesting. You also can nest more than one dictionaries in a list. You print("Yes, I have got 'scanner' in the office.")
can diversify the process of nesting by several methods.
else:
I am going to pack up multiple dictionaries inside a list. Coming to the back,
print("Sorry, I do not have that item.")
I will create three different dictionaries about different items of an office and
= RESTART: C:/Users/saifia computers/Desktop/[Link] type', 'drafting pads': 'It is blank', 'pen': 'parker', 'table': 'made of wood', 'table
lights': 'They are LED', 'office chair': 'boss'}
Yes, I have got 'scanner' in the office.
{'printer': 'Produced by HP', 'scanner': 'it is hybrid', 'laptop': 'dell', 'paper': 'A4
>>>
type', 'drafting pads': 'It is blank', 'pen': 'parker', 'table': 'made of wood', 'table
There is another method known as the clear() method that will empty your lights': 'They are LED', 'office chair': 'boss'}
dictionary. See the following code sample.
>>>
officeitem1 = {'printer' : 'Produced by HP', 'scanner': 'it is hybrid', 'laptop':
'dell', 'paper': 'A4 type', 'drafting pads': 'It is blank', 'pen': 'parker', 'table': There is another built-in method to create copy of the dictionary. The method
'made of wood', 'table lights': 'They are LED', 'office chair': 'boss'} is labeled as the dict() method.
officeitem1 = {'printer' : 'Produced by HP', 'scanner': 'it is hybrid', 'laptop':
print(officeitem1)
'dell', 'paper': 'A4 type', 'drafting pads': 'It is blank', 'pen': 'parker', 'table':
[Link]() 'made of wood', 'table lights': 'They are LED', 'office chair': 'boss'}
print(officeitem1) print(officeitem1)
= RESTART: C:/Users/saifia computers/Desktop/[Link] officeitem2 = dict(officeitem1)
{'printer': 'Produced by HP', 'scanner': 'it is hybrid', 'laptop': 'dell', 'paper': 'A4 print(officeitem2)
type', 'drafting pads': 'It is blank', 'pen': 'parker', 'table': 'made of wood', 'table
= RESTART: C:/Users/saifia computers/Desktop/[Link]
lights': 'They are LED', 'office chair': 'boss'}
{} {'printer': 'Produced by HP', 'scanner': 'it is hybrid', 'laptop': 'dell', 'paper': 'A4
type', 'drafting pads': 'It is blank', 'pen': 'parker', 'table': 'made of wood', 'table
>>> lights': 'They are LED', 'office chair': 'boss'}
You can see that the clear method has emptied the dictionary. Python allows {'printer': 'Produced by HP', 'scanner': 'it is hybrid', 'laptop': 'dell', 'paper': 'A4
you to create perfect copies of your dictionary. You can create as many type', 'drafting pads': 'It is blank', 'pen': 'parker', 'table': 'made of wood', 'table
copies as you want to. The method is dubbed as the copy() method. It is a lights': 'They are LED', 'office chair': 'boss'}
built-in Python method.
>>>
officeitem1 = {'printer' : 'Produced by HP', 'scanner': 'it is hybrid', 'laptop':
We had the exact copy of the same dictionary. There is a bit of difference in
'dell', 'paper': 'A4 type', 'drafting pads': 'It is blank', 'pen': 'parker', 'table':
writing the code.
'made of wood', 'table lights': 'They are LED', 'office chair': 'boss'}
If you have to create a dictionary from scratch, you can use the dict()
print(officeitem1)
constructor to do that. I will take an empty dictionary and fill it in with the
officeitem2 = [Link]() keys and values by using the dict() constructor.
print(officeitem2) officeitem1 = dict(printer = 'Produced by HP', scanner = 'it is hybrid', laptop
= RESTART: C:/Users/saifia computers/Desktop/[Link] = 'dell', paper = 'A4 type', draftingpads = 'blank', pen = 'parker', table = 'made
of wood')
{'printer': 'Produced by HP', 'scanner': 'it is hybrid', 'laptop': 'dell', 'paper': 'A4
print(officeitem1)
= RESTART: C:/Users/saifia computers/Desktop/[Link] Chapter Six: Input and Python Loops
{'printer': 'Produced by HP', 'scanner': 'it is hybrid', 'laptop': 'dell', 'paper': 'A4
type', 'draftingpads': 'blank', 'pen': 'parker', 'table': 'made of wood'} Programs are written to solve different problems. Some programs are made to
>>> collect information from users. These programs demand special functions
that could collect the information and process it to the system's database.
The keys should not contain any spaces while you are constructing a When you put your office on sale, you can introduce a special function that
dictionary by the dict() constructor. Please take a look at how I wrote drafting invites the buyers' quotations. The user input program will take the input,
pads. If you leave any spaces between the keys, Python interpreter will return analyze it, and respond to the user.
syntax error.
In this chapter, I’ll explain how you can build a program that accepts user
input and processes it. I will use the input() function to develop the program.
The user input and while loop will be explained together as it is the while
loop that keeps the program running. The while loop runs the program as
long as a particular condition stands true.
The input() Function
It is an interesting function and very helpful in program building. The
function pauses your program and allows the user to fill in the program with
the requisite information. Once the function receives the information, it
forwards it to a variable for storage purposes.
pgm = input("This program repeats whatever you write: ")
print(pgm)
= RESTART: C:/Users/saifia computers/Desktop/[Link]
This program repeats whatever you write: I am learning Python and I am
enjoying it well.
I am learning Python and I am enjoying it well.
>>>
= RESTART: C:/Users/saifia computers/Desktop/[Link]
This program repeats whatever you write: Do you know Python can be used
to educate robots.
Do you know Python can be used to educate robots.
>>>
I entered some statements which the program repeats as they are. The username = input(pgm)
important point is that you have to rerun the program once it has repeated one
print("I want to buy the office for " + username + " million dollars.")
statement. When you run the program, it pauses and waits for the user to
write something. Once the program senses input, it waits for the user to press = RESTART: C:/Users/saifia computers/Desktop/[Link]
Enter. After that, it displays the results. I will create a program that asks users If you are interested in buying the office, please proceed to fill in the price
to enter the bidding price to buy the office that has already been set up by the box.
player in your game.
Please enter the bidding price at which you want to buy the office. 3
pgm = input("Please enter the bidding price at which you want to buy the
office: ") I want to buy the office for 3 million dollars.
print("I want to buy the office at " + pgm + " million dollars.") >>>

= RESTART: C:/Users/saifia computers/Desktop/[Link] This is how you can easily build a multiline string in the user input function.
Please enter the bidding price at which you want to buy the office: five While Loops
I want to buy the office for five million dollars. This section will shed light on how you can create and use Python while
loops. You have already encountered the for loop which runs through a list of
>>> items and applies the code to each item in the list. The while loop is a bit
The program is suitable only if the user enters the value in the form of string. different. It runs through a set of items as long as a certain condition stands
Therefore you will have to leave a note, instructing the user to write only in true. While loop is interesting in the sense that you can use it to execute
words. However, there is a way out to solve this problem. You can allow different interesting mathematical functions. The simplest and the most
users to enter the price in numbers without causing an error. interesting thing is counting the numbers.
pgm = input("Please enter the bidding price at which you want to buy the my_number = 1
office: ") while my_number <= 15:
print("I want to buy the office at " + str(pgm) + " million dollars.") print(my_number)
= RESTART: C:/Users/saifia computers/Desktop/[Link] my_number += 1
Please enter the bidding price at which you want to buy the office: 5 = RESTART: C:/Users/saifia computers/Desktop/[Link]
I want to buy the office for 5 million dollars. 1
>>> 2
In the next sample, I will create a program that has more than lines. 3
pgm = input("If you are interested in buying the office, please proceed to fill 4
in the price box. ")
5
pgm += "\nPlease enter the bidding price at which you want to buy the office.
" 6
7 51
8 56
9 61
10 66
11 71
12 76
13 81
14 86
15 91
>>> 96
See another mathematical example of the use of a while loop. >>>
my_number = 1 I set the value to numbers 1 and 5, respectively. The while loop reads it and
while my_number <= 100: keeps running until it reaches 15 and 100, respectively. The code guides the
loop to calculate the numbers and display the result on the interpreter. The
print(my_number) loops get repeated as long as its condition remains true. Your player needs a
my_number += 5 while loop to exit the game. Only a while loop helps you end a game and
shutdown it properly. Otherwise, it will hang the system each time you try to
= RESTART: C:/Users/saifia computers/Desktop/[Link] shut it down.
1 This demands that you let the users quit the game when they want to. I will
6 not pack up the program in a while loop and then define the quit value for the
same so that users can exit it by entering the quit value.
11
pgm = input("This program repeats whatever you tell it: ")
16
pgm += "\nYou have to enter 'q' to exit the program. "
21
msg = ""
26
while msg != 'q':
31
msg = input(pgm)
36
print(msg)
41
46 = RESTART: C:/Users/saifia computers/Desktop/[Link]
This program repeats whatever you tell it: I am determined to learn Python in You have to enter 'q' to exit the program. What is your name?
six months.
What is your name?
I am determined to learn Python in six months.
hi
You have to enter 'q' to exit the program. I am determined to build my
You have to enter 'q' to exit the program. Are you fine?
programs in the first month of learning.
Are you fine?
I am determined to build my programs in the first month of learning.
hi
I am determined to learn Python in six months.
You have to enter 'q' to exit the program. I am looking forward to doing
You have to enter 'q' to exit the program. q business with you.
q I am looking forward to doing business with you.
>>> hi
I defined the prompt namely pgm in the first line of code. It gives the user You have to enter 'q' to exit the program. q
two options; one to enter a message and another to quit the program. I also
set a variable that stored the information the user enters. The while loop runs q
until the user enters q and breaks the loop. It can run a million times on end if >>>
the user does not end it.
You can see that the while loop ran until I entered the keyword q that broke
pgm = input("This program repeats whatever you tell it: ") the loop. The program is perfect except for the fact that it displays q as an
pgm += "\nYou have to enter 'q' to exit the program. " actual message. If I add an if clause to the code, it will work just fine.
msg = "" pgm = input("This program repeats whatever you tell it: ")
while msg != 'q': pgm += "\nYou have to enter 'q' to exit the program. "
msg = input(pgm) msg = ""
print(msg) while msg != 'q':
msg = input(pgm)
= RESTART: C:/Users/saifia computers/Desktop/[Link]
if msg != 'q':
This program repeats whatever you tell it: hi
print(msg)
hi
You have to enter 'q' to exit the program. how are you = RESTART: C:/Users/saifia computers/Desktop/[Link]
how are you This program repeats whatever you tell it: Hi
hi Hi
You have to enter 'q' to exit the program. My name is Jack. break
My name is Jack. else:
Hi print("I have purchased the " + [Link]())
You have to enter 'q' to exit the program. I am here to do business with you. = RESTART: C:/Users/saifia computers/Desktop/[Link]
I am here to do business with you. Please enter the name of the office item that you have purchased:table
Hi table
You have to enter 'q' to exit the program. I want to sell an office to the (You have to enter 'q' to exit the program.)
highest bidder. Have a look at the pictures.
I have purchased the
I want to sell an office to the highest bidder. Have a look at the pictures.
table
Hi
(You have to enter 'q' to exit the program.) laptop
You have to enter 'q' to exit the program. I think you are not interested. I have purchased the Laptop
Thank you!
table
I think you are not interested. Thank you!
(You have to enter 'q' to exit the program.) computer system
Hi
I have purchased the Computer System
You have to enter 'q' to exit the program. q
table
>>>
(You have to enter 'q' to exit the program.) stack of paper.
The program did not display the word q as a message. It simply lets the user
exit the program. I have purchased the Stack Of Paper.
The Break Keyword table
If you want to exit the loop without running the code that remains, you can (You have to enter 'q' to exit the program.) air conditioner
add a break statement to the program. The break statement tends to redirect I have purchased the Air Conditioner
the flow of a program and allow you to execute the code of your choice.
table
pgm = input("Please enter the name of the office item that you have
purchased:") (You have to enter 'q' to exit the program.) q
pgm += "\n(You have to enter 'q' to exit the program.) " >>>
while True: You have another choice as well. Instead of breaking out of the loop, you can
integrate into the block of code a continue statement that will take the code
item = input(pgm) back to the start after the condition stands tested. See the following
if item == 'q': mathematical example.
num = 0 26
while num < 40: 27
num += 1 29
if num %4 == 0: 30
continue 31
print(num) 33
= RESTART: C:/Users/saifia computers/Desktop/[Link] 34
1 35
2 37
3 38
5 39
6 >>>
7 You can see that the continue statement returned the code after a pause at the
point Python tested the condition. The num started at 0. I kept the figure
9
under 40 so the loop ran until 4, checked if the current number is divisible by
10 4 and then executed the rest of the code because the number was not divisible
11 by 4. Let us try another example to clear the concept fully.

13 num = 4
14 while num < 80:
15 num += 3
17 if num %4 == 0:
18 continue

19 print(num)

21 = RESTART: C:/Users/saifia computers/Desktop/[Link]


22 7
23 10
25 13
19 officeitems = items_tobuy.pop()
22 print("I am purchasing the " + [Link]())
25 items_bought.append(officeitems)
31 print("\nI have purchased the following items:")
34 for item_bought in items_bought:
37 print(item_bought.title())
43 = RESTART: C:/Users/saifia computers/Desktop/[Link]
46 I am purchasing the Office Chair
49 I have purchased the following items:
55 Office Chair
58 I am purchasing the Table Lights
61 I have purchased the following items:
67 Office Chair
70 Table Lights
73 I am purchasing the Table
79 I have purchased the following items:
82 Office Chair
>>> Table Lights
Loops, Lists, Dictionaries Table
The three go side by side. I have already given some code snippets that I am purchasing the Pen
showed what a while loop could be used for. I will give a comprehensive
I have purchased the following items:
overview of how you can pair up loops, lists, and dictionaries. The examples
will be a bit more complex than the previous examples. Office Chair
items_tobuy = ['printer', 'scanner', 'laptop', 'paper', 'drafting pads', 'pen', 'table', Table Lights
'table lights', 'office chair'] Table
items_bought = [] Pen
while items_tobuy: I am purchasing the Drafting Pads
I have purchased the following items: Table Lights
Office Chair Table
Table Lights Pen
Table Drafting Pads
Pen Paper
Drafting Pads Laptop
I am purchasing the Paper Scanner
I have purchased the following items: I am purchasing the Printer
Office Chair I have purchased the following items:
Table Lights Office Chair
Table Table Lights
Pen Table
Drafting Pads Pen
Paper Drafting Pads
I am purchasing the Laptop Paper
I have purchased the following items: Laptop
Office Chair Scanner
Table Lights Printer
Table >>>
Pen When a player purchases an item, he will get a clear message that an item has
been bought and added to the office. So, this has definitely made the game
Drafting Pads
more interesting.
Paper
While loop can also help you in removing multiple instances of a particular
Laptop value. If an item's value is being repeated in the list, you can set up a while
I am purchasing the Scanner loop to remove all instances of the same. For a small list, manually removing
it is not a problem. However, this feature of the while loops becomes a must
I have purchased the following items: when you are dealing with long lists.
Office Chair officeitems = ['printer', 'scanner', 'laptop', 'paper', 'drafting pads', 'scanner',
'pen', 'table', 'scanner', 'table lights', 'office chair'] print("I have purchased " + buyer_item + " from the brand " + officeitem
+ ".")
print(officeitems)
= RESTART: C:/Users/saifia computers/Desktop/[Link]
while 'scanner' in officeitems:
What do you want to buy? table
[Link]('scanner')
print(officeitems) Of what brand do you want to buy? interwood
Would you like to buy another item for the office? (yes/ noyes
= RESTART: C:/Users/saifia computers/Desktop/[Link]
What do you want to buy?
['printer', 'scanner', 'laptop', 'paper', 'drafting pads', 'scanner', 'pen', 'table',
'scanner', 'table lights', 'office chair'] = RESTART: C:/Users/saifia computers/Desktop/[Link]
['printer', 'laptop', 'paper', 'drafting pads', 'pen', 'table', 'table lights', 'office What do you want to buy? table
chair'] Of what brand do you want to buy? interwood
>>> Would you like to buy another item for the office? (yes/ no yes
In the next example, I will build a dictionary with the user input with a while What do you want to buy? air conditioner
loop. I will create a program that will ask the user to tell about the office
items he wants to buy and the brand name. The input will be forwarded to a Of what brand do you want to buy? orient
dictionary and used to create the desired output for the user. The program Would you like to buy another item for the office? (yes/ no yes
will display purchase statistics in a neat and summarized way.
What do you want to buy? laptop
officeitems = {}
Of what brand do you want to buy? dell
buying = True
Would you like to buy another item for the office? (yes/ no yes
while buying:
What do you want to buy? office chair
buyer_item = input("\nWhat do want to buy? ")
Of what brand do you want to buy? boss
officeitem = input("Of what brand do you want to buy? ")
Would you like to buy another item for the office? (yes/ no no
officeitems[buyer_item] = officeitem
Purchase Statistics
repeat = input("Would you like to buy another item for the office? (yes/
no ") I have purchased a table from the brand interwood.
if repeat == 'no': I have purchased an air conditioner from the brand orient.
buying = False I have purchased a laptop from the brand dell.
print("\nPurchase Statistics") I have purchased an office chair from the brand boss.

for buyer_item, officeitem in [Link](): >>>


The same program can be redesigned to collect names and email IDs of users What is your name? mark
who visit your eCommerce website. You can then use the information to send
what is your email id? mark@[Link]
your prospects direct mail ads and boost your business. All you need is a bit
of tweaking to the existing code and your program will be ready to boost Would you like to add another username or id? (yes/ no yes
your marketing campaign. What is your name? jasmine
users_id = {} what is your email id? jasmine@[Link]
info = True Would you like to add another username or id? (yes/ no
while info: User Info
user_name = input("\nWhat is your name? ") My name is johnson and my email ID is johnson@[Link].
user_id = input("what is your email id? ") My name is emily and my email ID is emily@[Link].
users_id[user_name] = user_id My name is emilia and my email ID is emilia@[Link].
repeat = input("Would you like to add another username or id? (yes/ no ") My name is mark and my email ID is mark@[Link].
if repeat == 'no': My name is jasmine and my email ID is jasmine@[Link].
info = False >>>
print("\nUser Info") You can see how easy it is to build a program with a while loop and user
for user_name, user_id in users_id.items(): input function to collect crucial prospect data that can ultimately help you
shape your marketing campaign. You can give this program a brilliant
print("My name is " + user_name + " and my email ID is " + user_id + interface and run it as part of your landing page design. As I have defined an
".") empty dictionary at the start, you can fill it with as much information as you
= RESTART: C:/Users/saifia computers/Desktop/[Link] want to. It can carry over a million items.
What is your name? johnson
what is your email id? johnson@[Link]
Would you like to add another username or id? (yes/ no yes
What is your name? emily
what is your email id? emily@[Link]
Would you like to add another username or id? (yes/ no yes
What is your name? emilia
what is your email id? emilia@[Link]
Would you like to add another username or id? (yes/ no yes
Chapter Seven: Python Functions now will no longer be empty. I will fill them up with some information.
def user_info(username):
This chapter will walk you through the process of writing functions. print("My name is " + [Link]() + " and I am a new user.")
Functions can be defined as blocks of code that have just one job to perform.
When you want to do a simple task that you have defined in your function, user_info('Joe')
you can just call the function you have written to do the job. If you are user_info('Jimmy')
looking forward to performing the same task more than once throughout the
user_info('Emily')
program, you can just make a call to the same function and Python will
execute the entire block of code. Functions make your programs simple and user_info('Emilia')
easy to write and run. user_info('Mark')
In this chapter, I will explain how you can create functions, pass crucial = RESTART: C:/Users/saifia computers/Desktop/[Link]
information to the same, and repeat multiple times the task that functions
perform. I will also explain how you can store a function in the form of My name is Joe and I am a new user.
modules. My name is Jimmy and I am a new user.
Defining Functions My name is Emily and I am a new user.
Defining a function is a simple job. The keyword I will use is called def. The My name is Emilia and I am a new user.
keyword will be followed by the name of the function and parenthesis.
Parenthesis is a function that is very important as it can be used for different My name is Mark and I am a new user.
purposes, like adding default information and passing information to >>>
functions at a later stage of writing a program.
The most important point to note here is that functions help you cut short the
def user_info(): block of code. You do not have to rewrite a block of code again and again to
print("My name is Joe and I am a new user.") do the same job. All you need is to call the function and use the parenthesis to
use new information for the same block of code. Programmers love functions
user_info() because they save their time and energy when they write lengthy programs.
= RESTART: C:/Users/saifia computers/Desktop/[Link] Arguments and Parameters
My name is Joe and I am a new user. I have packed up the variable inside the parenthesis and named it as the
>>> username; this is labeled as a parameter. The values Joe and Emily that I have
put in the parenthesis function are known as arguments. Arguments and
In the first line of code, I have defined the function. The second line carries parentheses are often confused with each other. People use them
the usual print statement while the last line is where I made a function call to interchangeably. That is not the right thing to do.
display the function's information. This can be dubbed as the simplest
structure of a function. The def keyword defines the function. There can be multiple arguments for a function; you can pass them to the
function in many ways and put them in a position. They are called positional
From this point, I will make it a bit complex by passing information to the arguments and they are also known as keyword arguments. Each argument
function. I will have to modify it a little bit to suit our needs. The parenthesis
may include the name of a variable, a list, or a dictionary. function calls are the most efficient way to do a job. As soon as a new user
Positional Arguments fills in the information and you make a function call, the entire block of code
will run and execute the information. There is virtually no limit to the number
When you make a function call, Python ought to watch the arguments with a of function calls. One important thing to keep in mind while making a
specific parameter in the definition of a function. The matching of values are function call is to remember the position of arguments. If you change the
dubbed as positional arguments. position, you are likely to get funny results.
def user_info(username, email_id): def user_info(username, email_id):
print("My name is " + [Link]() + " and I am a new user.") print("My name is " + [Link]() + " and I am a new user.")
print("My email ID is " + email_id.title() + ".") print("My email ID is " + email_id.title() + ".")
user_info('Joe', 'joe@[Link]') user_info('joe@[Link]', 'Joe')
user_info('Jimmy', 'jimmy@[Link]') user_info('jimmy@[Link]', 'Jimmy' )
user_info('Emily', 'emily@[Link]') user_info('emily@[Link]', 'Emily')
user_info('Emilia', 'emilia@[Link]') user_info('Emilia', 'emilia@[Link]')
user_info('Mark', 'mark@[Link]') user_info('Mark', 'mark@[Link]')
= RESTART: C:/Users/saifia computers/Desktop/[Link] >>>= RESTART: C:/Users/saifia computers/Desktop/[Link]
My name is Joe and I am a new user. My name is Joe@[Link] and I am a new user.
My email ID is Joe@[Link]. My email ID is Joe.
My name is Jimmy and I am a new user. My name is Jimmy@[Link] and I am a new user.
My email ID is Jimmy@[Link]. My email ID is Jimmy.
My name is Emily and I am a new user. My name is Emily@[Link] and I am a new user.
My email ID is Emily@[Link]. My email ID is Emily.
My name is Emilia and I am a new user. My name is Emilia and I am a new user.
My email ID is Emilia@[Link]. My email ID is Emilia@[Link].
My name is Mark and I am a new user. My name is Mark and I am a new user.
My email ID is Mark@[Link]. My email ID is Mark@[Link].
>>> >>>
The output neatly displays the name of the user and his or her email ID. In I have changed the position for the first three function calls and the results are
the above code sample, I have called the function more than once. Multiple ridiculous.
Keyword Arguments results. Keyword arguments help you create a functional program.
There is another way out. You can use keyword arguments to avoid this kind Default Values
of mix up. A keyword argument is like a name-value pair that is passed to a When you are writing a program, you may come up with information that
function. A keyword argument allows you to create a link between the name you have to use repeatedly. This means that you will have to fill in the
and the value inside an argument. When you pass the argument to the function call with the required arguments each you need that information to
function, Python cannot mistake it. It eliminates the confusion and you do not be executed. This may result in a waste of time and energy, and may also
have to worry about bringing your arguments in order. cause frustration. If you create default values for the function, you will be
def user_info(username, email_id): able to execute the excessively used information fast and efficiently. When
you leave the function call empty, it will use the default arguments. You can
print("My name is " + [Link]() + " and I am a new user.")
use the default information as many times as you want to. The default values
print("My email ID is " + email_id.title() + ".") tend to simply a program and declutter the code. I will fill in the same
user_info(email_id = 'joe@[Link]', username = 'Joe') example with the default arguments and also use the default values multiple
times.
user_info( email_id = 'jimmy@[Link]', username = 'Jimmy' )
def user_info(username = 'Dora', email_id = 'dora@[Link]'):
user_info( email_id = 'emily@[Link]', username = 'Emily')
print("My name is " + [Link]() + " and I am a new user.")
user_info(username = 'Emilia', email_id = 'emilia@[Link]')
print("My email ID is " + email_id.title() + ".")
user_info(username = 'Mark', email_id = 'mark@[Link]')
user_info(email_id = 'joe@[Link]', username = 'Joe')
= RESTART: C:/Users/saifia computers/Desktop/[Link]
user_info()
My name is Joe and I am a new user.
user_info( email_id = 'jimmy@[Link]', username = 'Jimmy' )
My email ID is Joe@[Link].
user_info()
My name is Jimmy and I am a new user.
user_info( email_id = 'emily@[Link]', username = 'Emily')
My email ID is Jimmy@[Link].
user_info(username = 'Emilia', email_id = 'emilia@[Link]')
My name is Emily and I am a new user.
user_info(username = 'Mark', email_id = 'mark@[Link]')
My email ID is Emily@[Link].
user_info()
My name is Emilia and I am a new user.
= RESTART: C:/Users/saifia computers/Desktop/[Link]
My email ID is Emilia@[Link].
My name is Joe and I am a new user.
My name is Mark and I am a new user.
My email ID is Joe@[Link].
My email ID is Mark@[Link].
My name is Dora and I am a new user.
>>>
My email ID is Dora@[Link].
I have changed the positions of the arguments and it hardly affected the
My name is Jimmy and I am a new user. = RESTART: C:/Users/saifia computers/Desktop/[Link]
My email ID is Jimmy@[Link]. My name is Joe and I am a new user.
My name is Dora and I am a new user. My email ID is Joe@[Link].
My email ID is Dora@[Link]. My name is Dora and I am a new user.
My name is Emily and I am a new user. My email ID is Dora@[Link].
My email ID is Emily@[Link]. My name is Jimmy and I am a new user.
My name is Emilia and I am a new user. My email ID is Dora@[Link].
My email ID is Emilia@[Link]. My name is Dora and I am a new user.
My name is Mark and I am a new user. My email ID is Dora@[Link].
My email ID is Mark@[Link]. My name is Emily and I am a new user.
My name is Dora and I am a new user. My email ID is Emily@[Link].
My email ID is Dora@[Link]. My name is Emilia and I am a new user.
>>> My email ID is Emilia@[Link].
You can use the keyword arguments, the positional arguments and the default My name is Mark and I am a new user.
values at the same time. My email ID is Mark@[Link].
def user_info(username = 'Dora', email_id = 'dora@[Link]'):
My name is Dora and I am a new user.
print("My name is " + [Link]() + " and I am a new user.") My email ID is Dora@[Link].
print("My email ID is " + email_id.title() + ".") >>>
user_info(email_id = 'joe@[Link]', username = 'Joe')
The most important thing to note in the code mentioned above is that in one
user_info() function call when I missed out on writing the email ID, the program picked
user_info( username = 'Jimmy' ) it up from the default values and ran it. If you leave one argument in the
function call but have a default argument in place, you will have it covered
user_info() by the default values.
user_info( email_id = 'emily@[Link]', username = 'Emily') You may run an error if you fail to fill in the function call with the
user_info('Emilia', email_id = 'emilia@[Link]') arguments.
user_info('Mark', 'mark@[Link]') def user_info(username, email_id ):
user_info() print("My name is " + [Link]() + " and I am a new user.")
print("My email ID is " + email_id.title() + ".")
user_info() My Name Is Jimmy And I Am A New User, And My Email Id Is
Jimmy@[Link].
= RESTART: C:/Users/saifia computers/Desktop/[Link]
>>>
Traceback (most recent call last):
In the next code sample, I will add another argument to the code. I will also
File "C:/Users/saifia computers/Desktop/[Link]", line 6, in <module>
experiment on making an argument optional so that the users who do not
user_info() want to fill in a value, can leave it without running an error in the program.
TypeError: user_info() missing 2 required positional arguments: 'username' def user_info(username, email_id, gender ):
and 'email_id'
info = "My name is " + [Link]() + " and I am a new user, and my
>>> email ID is " + email_id.title() + ". My gender is " + [Link]() + "."
Returning Values return [Link]()
A function does not have to display the output in a direct form. You can newuser = user_info('Dora', 'dora@[Link]', 'female')
make the function process a bunch of data and return the value in an indirect
form. The return statement picks up a value from the function and forwards it print(newuser)
to the line that made a function call. newuser1 = user_info('John', 'john@[Link]', 'male')
def user_info(username, email_id ): print(newuser1)
info = "My name is " + [Link]() + " and I am a new user, and my newuser2 = user_info('Jimmy', 'jimmy@[Link]', 'male')
email ID is " + email_id.title() + "." print(newuser2)
return [Link]() = RESTART: C:/Users/saifia computers/Desktop/[Link]
newuser = user_info('Dora', 'dora@[Link]') My Name Is Dora And I Am A New User, And My Email Id Is
print(newuser) Dora@[Link]. My Gender Is Female.
newuser1 = user_info('John', 'john@[Link]') My Name Is John And I Am A New User, And My Email Id Is
John@[Link]. My Gender Is Male.
print(newuser1)
newuser2 = user_info('Jimmy', 'jimmy@[Link]') My Name Is Jimmy And I Am A New User, And My Email Id Is
Jimmy@[Link]. My Gender Is Male.
print(newuser2)
>>>
= RESTART: C:/Users/saifia computers/Desktop/[Link]
Suppose someone wants to leave the email option aside. You can add a
My Name Is Dora And I Am A New User, And My Email Id Is conditional statement to the existing code to allow users to make a choice at
Dora@[Link]. will.
My Name Is John And I Am A New User, And My Email Id Is def user_info(username, gender, email_id='' ):
John@[Link].
if email_id:
info = "My name is " + [Link]() + " and I am a new user, and print(newuser1)
my email ID is " + email_id.title() + ". My gender is " + [Link]() + "."
newuser2 = user_info('Jimmy', 'jimmy@[Link]', 'male')
else:
print(newuser2)
info = "My name is " + [Link]() + " and my gender is " +
newuser3 = user_info('Dora', 'dora@[Link]', 'female')
[Link]() + "."
print(newuser3)
return [Link]()
= RESTART: C:/Users/saifia computers/Desktop/[Link]
newuser = user_info('Dora', 'female')
{'uname': 'Johnson', 'gender': 'johnson@[Link]', 'email address': 'male'}
print(newuser)
{'uname': 'John', 'gender': 'john@[Link]', 'email address': 'male'}
newuser1 = user_info('John', 'john@[Link]', 'male')
{'uname': 'Jimmy', 'gender': 'jimmy@[Link]', 'email address': 'male'}
print(newuser1)
{'uname': 'Dora', 'gender': 'dora@[Link]', 'email address': 'female'}
newuser2 = user_info('Jimmy', 'jimmy@[Link]', 'male')
>>>
print(newuser2)
The function user_info takes the requisite information about the name, gender
= RESTART: C:/Users/saifia computers/Desktop/[Link]
and email address of a user, and fill them up into a dictionary. Each value is
My Name Is Dora And My Gender Is Female. stored in the designated key. The function receives information in raw form
and turns it into textual information in a meaningful data structure. Up till
My Name Is John And I Am A New User, And My Email Id Is Male. My
Gender Is John@[Link]. now, I have stored and processed the information in the form of strings. You
may confront situations where you have to store data in numerical form as
My Name Is Jimmy And I Am A New User, And My Email Id Is Male. My well. There is an easy way out.
Gender Is Jimmy@[Link].
def user_info(username, gender, email_id, age=''):
>>>
user = {'uname': username, 'gender': gender, 'email address': email_id}
Function and Dictionary
if age:
You can pair up a dictionary with a function. Take the example of the
following function. user['age'] = age

def user_info(username, gender, email_id): return user

user = {'uname': username, 'gender': gender, 'email address': email_id} newuser = user_info('Johnson', 'johnson@[Link]', 'male', age=55)

return user print(newuser)

newuser = user_info('Johnson', 'johnson@[Link]', 'male') newuser1 = user_info('John', 'john@[Link]', 'male', age=33)

print(newuser) print(newuser1)

newuser1 = user_info('John', 'john@[Link]', 'male') newuser2 = user_info('Jimmy', 'jimmy@[Link]', 'male', age= 54)
print(newuser2) print("\n The user information is as follows: " + newuser + ".")
newuser3 = user_info('Dora', 'dora@[Link]', 'female', age= 24) = RESTART: C:/Users/saifia computers/Desktop/[Link]
print(newuser3) Please tell me about yourself.
= RESTART: C:/Users/saifia computers/Desktop/[Link] Please enter your name: John
{'uname': 'Johnson', 'gender': 'johnson@[Link]', 'email address': 'male', Please enter your email address: john@[Link]
'age': 55} Please enter your gender: male
{'uname': 'John', 'gender': 'john@[Link]', 'email address': 'male', 'age': 33} Please tell me about yourself.
{'uname': 'Jimmy', 'gender': 'jimmy@[Link]', 'email address': 'male', 'age':
Please enter your name: jimmy
54}
Please enter your email address: jimmy@[Link]
{'uname': 'Dora', 'gender': 'dora@[Link]', 'email address': 'female', 'age':
24} Please enter your gender: male
>>> Please tell me about yourself.
I have added a new parameter to the function's definition and have also Please enter your name: dora
assigned this parameter a kind of empty default value. Please enter your email address: dora@[Link]
Function and While Loop Please enter your gender: female
You can pair up a function with a while loop. Let us jump to the text editor to Please tell me about yourself.
see how you can do that.
Please enter your name:
def user_info(username, email_id, gender ):
The while loop lacks a quit condition therefore it will run on end and will
info = "My name is " + [Link]() + " and I am a new user, and my keep asking about the name of users even after all the users have filled in
email ID is " + email_id.title() + ". My gender is " + [Link]() + "." their personal information. I will add a break statement in the same code so
return [Link]() that users can exit the program when they have entered all the information.
while True: def user_info(username, email_id, gender ):
print("\nPlease tell me about yourself.") info = "My name is " + [Link]() + " and I am a new user, and my
email ID is " + email_id.title() + ". My gender is " + [Link]() + "."
user_name = input("Please enter your name: ")
return [Link]()
email = input("Please enter your email address: ")
while True:
gen = input("Please enter your gender: ")
print("\nPlease tell me about yourself.")
newuser = user_info(user_name, email, gen) print("(If you want to exit the program, enter 'q')")
uname = input("Please enter your name: ") Hi, My name is Johnson. I am here to take a walk-in-interview.
if uname == 'q': Hi, My name is James. I am here to take a walk-in-interview.
break >>>
If you run into an error, it can possibly be due to a missing argument. See the
uemail = input("Please enter your email address: ") following error type.
if uemail == 'q': def user_info(usersinfo):
break for userinfo in usersinfo:
ugen = input("Please enter your gender: ") mg = "Hi, My name is " + [Link]() + ". I am here to take a walk-
if ugen == 'q': in interview."
break print(mg)
candidate_names = ['jimmy', 'john', 'dora', 'johnson', 'james']
newuser = user_info(uname, uemail, ugen)
user_info()
print("\n The user information is as follows: " + newuser + ".")
= RESTART: C:/Users/saifia computers/Desktop/[Link]
This program will keep running until someone enters ‘q.’ Functions are
Traceback (most recent call last):
flexible in inviting and using different types of data structures. You can easily
pass a list to a specific function. Whether the list is of numbers, names, and File "C:/Users/saifia computers/Desktop/[Link]", line 7, in <module>
even complex objects like dictionaries. When you do that, the function gets user_info()
access to the specific contents of the list.
TypeError: user_info() missing 1 required positional argument: 'usersinfo'
def user_info(usersinfo):
>>>
for userinfo in usersinfo:
Therefore, you should not leave the parenthesis of the function empty.
mg = "Hi, My name is " + [Link]() + ". I am here to take a walk-
in interview." Functions allow you to modify different data types such as lists. You can first
pass a list and then modify it as well. The changes you introduce to a list are
print(mg) permanent and allow a person to work efficiently. The following will pass the
candidate_names = ['jimmy', 'john', 'dora', 'johnson', 'james'] list without functions.
user_info(candidate_names) to_buy_items = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system',
'table lights']
= RESTART: C:/Users/saifia computers/Desktop/[Link]
bought_items = []
Hi, My name is Jimmy. I am here to take a walk-in-interview.
while to_buy_items:
Hi, My name is John. I am here to take a walk-in-interview.
office = to_buy_items.pop()
Hi, My name is Dora. I am here to take a walk-in-interview.
print("I am buying the " + office) office = to_buy_items.pop()
bought_items.append(office) print("I am buying the " + office)
print("\nI have purchased and set up the following items in the office:") bought_items.append(office)
for bought_item in bought_items: def o_bought_items(bought_items):
print(bought_item) print("\nI have purchased and set up the following items in the office:")
= RESTART: C:/Users/saifia computers/Desktop/[Link] for bought_item in bought_items:
I am buying the table lights print(bought_item)
I am buying the computer system to_buy_items = ['printer', 'scanner', 'fan', 'table', 'chair', 'computer system',
'table lights']
I am buying the chair
bought_items = []
I am buying the table
I am buying the fan officeitems(to_buy_items, bought_items)

I am buying the scanner o_bought_items(bought_items)

I am buying the printer = RESTART: C:/Users/saifia computers/Desktop/[Link]


I am buying the table lights
I have purchased and set up the following items in the office:
table lights I am buying the computer system
I am buying the chair
computer system
chair I am buying the table

table I am buying the fan


I am buying the scanner
fan
scanner I am buying the printer
I have purchased and set up the following items in the office:
printer
>>> table lights

Now I will write two functions for two separate jobs. The code will be more computer system
efficient and interactive. chair
def officeitems (to_buy_items, bought_items): table
while to_buy_items: fan
scanner Chapter Eight: Object-Oriented Programming
printer
>>> Object-oriented programming is the spirit of Python. It is one of the most
effective approaches to develop software. Object-oriented programming
suggests that you write effective classes to represent real-world situations and
objects. While writing a class, you get the actual feel of automation. You get
to build an object from a class and add appropriate personality traits to the
same. The process of building objects from a class is dubbed as instantiation.
In this chapter, I will explain how to write Python classes and how to create a
lot of instances in a single class. I will also define the actions that I want to
attribute to an object. You will also be able to store the classes in the form of
modules and then import them to your program files.
Python classes help you build complex programs and give you a feel for
programming. You will get to know your code and the bigger concepts
behind these codes. Classes can help you wrap up a lot of work in a short
amount of time and meet complex challenges in the simplest ways. A class
can turn a random program into sophisticated software.
You can model any real-world object with the help of Python classes. In the
next code snippet, I will write a code that will be modeled on a leopard. I will
give the leopard a name, age, and color. I will add behavioral attributes to the
class as well.
Leopard Class
After writing the leopard class, I will add instances to the same that will store
the name, age and color of the object.
class Leopard():
"""This class will build the model of a leopard."""
def__init__(self, lname, lage, lcolor):
"""here I will initialize the name, age and color attributes of the
class."""
[Link] = lname
[Link] = lage
[Link] = lcolor def run(self):
def run(self): print([Link]() + " is running fast out in the wild.")
print([Link]() + " is running fast out in the wild.") def attack(self):
def attack(self): print([Link]() + " is now attacking a deer who is grazing in the
print([Link]() + " is now attacking a deer who is grazing in the meadow.")
meadow.") leopard1 = Leopard('Tame', 9, 'yellow')
This is how you can write a class and add attributes to it. I have created the print("The name of the leopard is " + [Link]() + ".")
class and add a couple of functions. print("The age of the leopard is " + str([Link]) + ".")
Explaining the __init__() Method print("The color of the leopard is " + [Link]() + ".")
It is a special method that is automatically run by Python when you create a = RESTART: C:/Users/saifia computers/Desktop/[Link]
new instance from the main Leopard class. The method two underscores in
the front and two in the trail. The name of the leopard is Tame.
I have defined the __init__() method and given it three attributes for the The age of the leopard is 9.
name, age, and the color of the leopard. Then I added two more methods that The color of the leopard is Yellow.
are about the behavioral traits of the leopard we are creating. These methods
will print messages about the running and attacking of the leopard. If you >>>
want to understand it in a simpler form, you can consider the leopard a robot Now I will add more instances to the same class.
leopard. This will help you understand how Python helps in automating
class Leopard():
machines by modeling them on real-life objects.
Now that we have the structure of the class, we can move on to create """This class will build the model of a leopard."""
different objects. I will add an instance to the Leopard class.
def __init__(self, lname, lage, lcolor):
class Leopard():
"""here I will initialize the name, age and color attributes of the
"""This class will build the model of a leopard.""" class."""

def __init__(self, lname, lage, lcolor): [Link] = lname

"""here I will initialize the name, age and color attributes of the [Link] = lage
class.""" [Link] = lcolor
[Link] = lname def run(self):
[Link] = lage print([Link]() + " is running fast out in the wild.")
[Link] = lcolor def attack(self):
print([Link]() + " is now attacking a deer who is grazing in the Now that I have created an instance for the Leopard class, I will now add to it
meadow.") some additional methods that will make the robot leopard run wildly and
leopard1 = Leopard('Tame', 9, 'yellow') attack the prey to hunt his meal. This is going to be quite interesting.

print("The name of the leopard is " + [Link]() + ".") class Leopard():

print("The age of the leopard is " + str([Link]) + ".") """This class will build the model of a leopard."""

print("The color of the leopard is " + [Link]() + ".") def __init__(self, lname, lage, lcolor):

leopard2 = Leopard('Fame', 8, 'snow white') """here I will initialize the name, age and color attributes of the
class."""
print("The name of the leopard is " + [Link]() + ".")
[Link] = lname
print("The age of the leopard is " + str([Link]) + ".")
[Link] = lage
print("The color of the leopard is " + [Link]() + ".")
[Link] = lcolor
leopard3 = Leopard('Storm', 11, 'yellow') def run(self):
print("The name of the leopard is " + [Link]() + ".") print([Link]() + " is running fast out in the wild.")
print("The age of the leopard is " + str([Link]) + ".") def attack(self):
print("The color of the leopard is " + [Link]() + ".") print([Link]() + " is now attacking a deer who is grazing in the
meadow.")
= RESTART: C:/Users/saifia computers/Desktop/[Link]
leopard1 = Leopard('Tame', 9, 'yellow')
The name of the leopard is Tame.
print("The name of the leopard is " + [Link]() + ".")
The age of the leopard is 9.
print("The age of the leopard is " + str([Link]) + ".")
The color of the leopard is Yellow.
print("The color of the leopard is " + [Link]() + ".")
The name of the leopard is Fame.
[Link]()
The age of the leopard is 8.
[Link]()
The color of the leopard is Snow White.
The name of the leopard is Storm. leopard2 = Leopard('Fame', 8, 'snow white')
The age of the leopard is 11. print("The name of the leopard is " + [Link]() + ".")
The color of the leopard is Yellow. print("The age of the leopard is " + str([Link]) + ".")
>>> print("The color of the leopard is " + [Link]() + ".")
[Link]() the leopard same. See the following example.
[Link]() class Leopard():
leopard3 = Leopard('Storm', 11, 'yellow') """This class will build the model of a leopard."""
print("The name of the leopard is " + [Link]() + ".")
def __init__(self, lname, lage, lcolor):
print("The age of the leopard is " + str([Link]) + ".")
"""here I will initialize the name, age and color attributes of the
print("The color of the leopard is " + [Link]() + ".") class."""
[Link]() [Link] = lname
[Link]() [Link] = lage
= RESTART: C:/Users/saifia computers/Desktop/[Link] [Link] = lcolor
The name of the leopard is Tame. def run(self):
The age of the leopard is 9. print([Link]() + " is running fast out in the wild.")
The color of the leopard is Yellow. def attack(self):
Tame is running fast out in the wild. print([Link]() + " is now attacking a deer who is grazing in the
Tame is now attacking a deer who is grazing in the meadow. meadow.")
The name of the leopard is Fame. leopard1 = Leopard('Tame', 9, 'yellow')
The age of the leopard is 8. print("The name of the leopard is " + [Link]() + ".")
The color of the leopard is Snow White. print("The age of the leopard is " + str([Link]) + ".")
Fame is running fast out in the wild. print("The color of the leopard is " + [Link]() + ".")
Fame is now attacking a deer who is grazing in the meadow. leopard2 = Leopard('Tame', 9, 'yellow')
The name of the leopard is Storm. print("The name of the leopard is " + [Link]() + ".")
The age of the leopard is 11. print("The age of the leopard is " + str([Link]) + ".")
The color of the leopard is Yellow. print("The color of the leopard is " + [Link]() + ".")
Storm is running fast out in the wild. = RESTART: C:/Users/saifia computers/Desktop/[Link]
Storm is now attacking a deer who is grazing in the meadow. The name of the leopard is Tame.
>>> The age of the leopard is 9.
Python creates two separate instances if you keep the name, age and color of The color of the leopard is Yellow.
The name of the leopard is Tame. print("The age of the fish is " + str([Link]) + ".")
The age of the leopard is 9. print("The color of the fish is " + [Link]() + ".")
The color of the leopard is Yellow. [Link]()
>>> [Link]()
The Fish Class = RESTART: C:/Users/saifia computers/Desktop/[Link]
class Fish(): The name of the fish is Tuna.
"""This class will build the model of a leopard.""" The age of the fish is 2.
The color of the fish is Yellow.
def __init__(self, fname, fage, fcolor):
Tuna is swimming at a fast pace against the current.
"""here I will initialize the name, age and color attributes of the
class.""" Tuna is hunting smaller fish to feed itself.
[Link] = fname The name of the fish is Whale.

[Link] = fage The age of the fish is 50.

[Link] = fcolor The color of the fish is Blue & White.


def swim(self): Whale is swimming at a fast pace against the current.

print([Link]() + " is swimming at a fast pace against the Whale is hunting smaller fish to feed itself.
current.") >>>
def hunt(self): The Bike Class
print([Link]() + " is hunting smaller fish to feed itself.") In this code sample, I will create bike class. I will add the model name, make,
fish1 = Fish('Tuna', 2, 'yellow') color and year of manufacturing to the class and display the information in a
neatly formatted form.
print("The name of the fish is " + [Link]() + ".")
class Bike():
print("The age of the fish is " + str([Link]) + ".")
"""This class will build the model of a bike."""
print("The color of the fish is " + [Link]() + ".")
[Link]() def __init__(self, bmodel, bmake, bcolor, byear):
[Link]()
[Link] = bmodel
fish2 = Fish('whale', 50, 'blue & white')
[Link] = bmake
print("The name of the fish is " + [Link]() + ".")
[Link] = bcolor
[Link] = byear bike1 = Bike('CG-125', 'blue', 2012)
def fullname(self): print([Link]())
fullbikename = str([Link]) + ' ' + [Link] + ' ' + [Link] + ' ' >>>= RESTART: C:/Users/saifia computers/Desktop/[Link]
+ [Link]
Traceback (most recent call last):
return [Link]() File "C:/Users/saifia computers/Desktop/[Link]", line 16, in <module>

bike1 = Bike('CG-125', 'Honda', 'blue', 2012) bike1 = Bike('CG-125', 'blue', 2012)

print([Link]()) TypeError: __init__() missing 1 required positional argument: 'byear'


= RESTART: C:/Users/saifia computers/Desktop/[Link] >>>
2012 Cg-125 Honda Blue Just like the Leopard class, you can create as many instances for the Bike
class as you need. This program is helpful if you are looking forward to
>>> owning a bike showroom. You can fill in the bike class with the latest
The process is similar to that of the creation of a Leopard class. I have information whenever a new bike gets registered with the showroom for sale.
defined the __init__ () method and the self-parameters. Four parameters will This is how you allow your customers to view each bike and its specifications
define the make, model, color and year of making of the bike. When you are in a fast and efficient way. I will now add more instances to the Bike class to
creating a new instance to the bike class, you will have to define the make, show how you can store more information to the database through a working
model, year and color of the bike. If you miss one of the parameters while Bike class.
creating an instance, you will see an interpreter error just like the following. class Bike():
class Bike(): """This class will build the model of a bike."""
"""This class will build the model of a bike."""
def __init__(self, bmodel, bmake, bcolor, byear):
def __init__(self, bmodel, bmake, bcolor, byear):
[Link] = bmodel
[Link] = bmodel [Link] = bmake
[Link] = bmake [Link] = bcolor
[Link] = bcolor [Link] = byear
[Link] = byear def fullname(self):
def fullname(self): fullbikename = "We have a bike that hit the markets in " +
fullbikename = str([Link]) + ' ' + [Link] + ' ' + [Link] + ' ' str([Link]) + ". The model is " + [Link] + ". The bike is
+ [Link] manufactured by " + [Link] + ". Its color is " + [Link] + "."
return [Link]() return [Link]()
bike1 = Bike('CG-125', 'Honda', 'blue', 2012) """This class will build the model of a bike."""
print([Link]())
def __init__(self, bmodel, bmake, bcolor, byear):
bike2 = Bike('F 900 R', 'BMW', 'black', 2014)
print([Link]()) [Link] = bmodel
bike3 = Bike('F 900 XR', 'BMW', 'blue', 2014) [Link] = bmake
print([Link]()) [Link] = bcolor
bike4 = Bike('R 1250 RT', 'BMW', 'brown', 2016) [Link] = byear
print([Link]()) self.odometer_reading = 0
bike5 = Bike('Heritage Classic', 'Harley Davidson', 'black', 2018) def fullname(self):
print([Link]()) fullbikename = "We have a bike that hit the markets in " +
= RESTART: C:/Users/saifia computers/Desktop/[Link] str([Link]) + ". The model is " + [Link] + ". The bike is
manufactured by " + [Link] + ". Its color is " + [Link] + "."
We Have A Bike That Hit The Markets In 2012. The Model Is Cg-125. The
Bike Is Manufactured By Honda. Its Color Is Blue. return [Link]()

We Have A Bike That Hit The Markets In 2014. The Model Is F 900 R. The def read_odometer(self):
Bike Is Manufactured By BMW. Its Color Is Black. print("This bike has run " + str(self.odometer_reading) + " kilometers
We Have A Bike That Hit The Markets In 2014. The Model Is F 900 Xr. The on the road.")
Bike Is Manufactured By BMW. Its Color Is Blue.
bike1 = Bike('CG-125', 'Honda', 'blue', 2012)
We Have A Bike That Hit The Markets In 2016. The Model Is R 1250 Rt.
The Bike Is Manufactured By BMW. Its Color Is Brown. print([Link]())
We Have A Bike That Hit The Markets In 2016. The Model Is R 1250 Rt. bike1.read_odometer()
The Bike Is Manufactured By BMW. Its Color Is Brown. bike2 = Bike('F 900 R', 'BMW', 'black', 2014)
>>> print([Link]())
Each attribute in the Bike class demands an initial value. You can set the bike2.read_odometer()
initial value at zero. It also can be an empty string. When you are running a
showroom, you need to tell your customers how many kilometers the bike bike3 = Bike('F 900 XR', 'BMW', 'blue', 2014)
has run on the road. To achieve this objective, you can integrate a method print([Link]())
into the program. See the changes in the code. I will include an odometer
reading method for the Bike class. bike3.read_odometer()

class Bike(): bike4 = Bike('R 1250 RT', 'BMW', 'brown', 2016)


print([Link]()) You can directly change the value of the attribute by an instance. You can set
its value with the help of a method or increment the same by a method. In the
bike4.read_odometer()
following code sample, I will test how we can make the above-mentioned
bike5 = Bike('Heritage Classic', 'Harley Davidson', 'black', 2018) changes. I have also changed the read_odometer() method to
print([Link]()) reading_odometer() method to make more current and interactive.
bike5.read_odometer() class Bike():
= RESTART: C:/Users/saifia computers/Desktop/[Link] """This class will build the model of a bike."""
We Have A Bike That Hit The Markets In 2012. The Model Is Cg-125. The
def __init__(self, bmodel, bmake, bcolor, byear):
Bike Is Manufactured By Honda. Its Color Is Blue.
This bike has run 0 kilometers on the road. [Link] = bmodel
We Have A Bike That Hit The Markets In 2014. The Model Is F 900 R. The [Link] = bmake
Bike Is Manufactured By BMW. Its Color Is Black.
[Link] = bcolor
This bike has run 0 kilometers on the road.
[Link] = byear
We Have A Bike That Hit The Markets In 2014. The Model Is F 900 Xr. The
Bike Is Manufactured By BMW. Its Color Is Blue. self.odometer_reading = 0

This bike has run 0 kilometers on the road. def fullname(self):

We Have A Bike That Hit The Markets In 2016. The Model Is R 1250 Rt. fullbikename = "We have a bike that hit the markets in " +
The Bike Is Manufactured By BMW. Its Color Is Brown. str([Link]) + ". The model is " + [Link] + ". The bike is
manufactured by " + [Link] + ". Its color is " + [Link] + "."
This bike has run 0 kilometers on the road.
return [Link]()
We Have A Bike That Hit The Markets In 2016. The Model Is R 1250 Rt.
The Bike Is Manufactured By BMW. Its Color Is Brown. def reading_odometer(self):

This bike has run 0 kilometers on the road. print("This bike has run " + str(self.odometer_reading) + " kilometers
on the road.")
>>>
Python calls the __init__() method to form a new instance. It stores the bike1 = Bike('CG-125', 'Honda', 'blue', 2012)
values in the form of attributes just as it did for the past example. Python has print([Link]())
now created a new attribute and adjusts its value to zero. Coupled with the
attribute comes a new method, namely read_odometer(). This is how your bike1.odometer_reading = 21
customers can easily read the mileage of the bike. It is also helpful for you, as bike1.reading_odometer()
you can easily track how many miles your car has run.
bike2 = Bike('F 900 R', 'BMW', 'black', 2014)
You have the power to change the value of the attributes in different ways.
print([Link]())
bike2.odometer_reading = 27 >>>
bike2.reading_odometer() You can also change the default value at 50 kilometers to manage the
difference of mileage consumed in transporting the bike from one place to
bike3 = Bike('F 900 XR', 'BMW', 'blue', 2014)
another.
print([Link]())
class Bike():
bike3.odometer_reading = 30
"""This class will build the model of a bike."""
bike3.reading_odometer()
bike4 = Bike('R 1250 RT', 'BMW', 'brown', 2016) def __init__(self, bmodel, bmake, bcolor, byear):
print([Link]())
[Link] = bmodel
bike4.reading_odometer()
[Link] = bmake
bike5 = Bike('Heritage Classic', 'Harley Davidson', 'black', 2018)
[Link] = bcolor
print([Link]())
[Link] = byear
bike5.reading_odometer()
self.odometer_reading = 50
>>>= RESTART: C:/Users/saifia computers/Desktop/[Link]
def fullname(self):
We Have A Bike That Hit The Markets In 2012. The Model Is Cg-125. The
Bike Is Manufactured By Honda. Its Color Is Blue. fullbikename = "We have a bike that hit the markets in " +
str([Link]) + ". The model is " + [Link] + ". The bike is
This bike has run 21 kilometers on the road. manufactured by " + [Link] + ". Its color is " + [Link] + "."
We Have A Bike That Hit The Markets In 2014. The Model Is F 900 R. The return [Link]()
Bike Is Manufactured By BMW. Its Color Is Black.
def reading_odometer(self):
This bike has run 27 kilometers on the road.
print("This bike has run " + str(self.odometer_reading) + " kilometers
We Have A Bike That Hit The Markets In 2014. The Model Is F 900 Xr. The on the road.")
Bike Is Manufactured By BMW. Its Color Is Blue.
This bike has run 30 kilometers on the road. bike1 = Bike('CG-125', 'Honda', 'blue', 2012)
We Have A Bike That Hit The Markets In 2016. The Model Is R 1250 Rt. print([Link]())
The Bike Is Manufactured By BMW. Its Color Is Brown. bike1.odometer_reading = 100
This bike has run 0 kilometers on the road. bike1.reading_odometer()
We Have A Bike That Hit The Markets In 2016. The Model Is R 1250 Rt. bike2 = Bike('F 900 R', 'BMW', 'black', 2014)
The Bike Is Manufactured By BMW. Its Color Is Brown.
print([Link]())
This bike has run 0 kilometers on the road.
bike2.odometer_reading = 500 >>>
bike2.reading_odometer() Proper Modification of Values
bike3 = Bike('F 900 XR', 'BMW', 'blue', 2014) It is quite helpful to have a bunch of methods that would update different
attributes of your program. Instead of directly accessing multiple attributes,
print([Link]())
you can pass the latest value to a newly added method and let it handle
bike3.odometer_reading = 700 updating the program. The program will do the updating internally and you
bike3.reading_odometer() do not have to worry about it anymore. The new method will be dubbed as
updating_the_odometer().
bike4 = Bike('R 1250 RT', 'BMW', 'brown', 2016)
class Bike():
print([Link]())
"""This class will build the model of a bike."""
bike4.reading_odometer()
bike5 = Bike('Heritage Classic', 'Harley Davidson', 'black', 2018) def __init__(self, bmodel, bmake, bcolor, byear):
print([Link]())
[Link] = bmodel
bike5.reading_odometer()
[Link] = bmake
= RESTART: C:/Users/saifia computers/Desktop/[Link]
[Link] = bcolor
We Have A Bike That Hit The Markets In 2012. The Model Is Cg-125. The
Bike Is Manufactured By Honda. Its Color Is Blue. [Link] = byear
This bike has run 100 kilometers on the road. self.odometer_reading = 50
We Have A Bike That Hit The Markets In 2014. The Model Is F 900 R. The def fullname(self):
Bike Is Manufactured By BMW. Its Color Is Black. fullbikename = "We have a bike that hit the markets in " +
This bike has run 500 kilometers on the road. str([Link]) + ". The model is " + [Link] + ". The bike is
manufactured by " + [Link] + ". Its color is " + [Link] + "."
We Have A Bike That Hit The Markets In 2014. The Model Is F 900 Xr. The
Bike Is Manufactured By BMW. Its Color Is Blue. return [Link]()
This bike has run 700 kilometers on the road. def reading_odometer(self):
We Have A Bike That Hit The Markets In 2016. The Model Is R 1250 Rt. print("This bike has run" + str(self.odometer_reading) + " kilometers
The Bike Is Manufactured By BMW. Its Color Is Brown. on the road.")
This bike has run 50 kilometers on the road. def updating_the_odometer(self, bmileage):
We Have A Bike That Hit The Markets In 2016. The Model Is R 1250 Rt. self.odometer_reading = bmileage
The Bike Is Manufactured By BMW. Its Color Is Brown.
bike1 = Bike('CG-125', 'Honda', 'blue', 2012)
This bike has run 50 kilometers on the road.
print([Link]()) We Have A Bike That Hit The Markets In 2016. The Model Is R 1250 Rt.
The Bike Is Manufactured By BMW. Its Color Is Brown.
bike1.updating_the_odometer(100)
This bike has 50 kilometers on the road.
bike1.reading_odometer()
We Have A Bike That Hit The Markets In 2016. The Model Is R 1250 Rt.
bike2 = Bike('F 900 R', 'BMW', 'black', 2014)
The Bike Is Manufactured By BMW. Its Color Is Brown.
print([Link]())
This bike has 50 kilometers on the road.
bike2.updating_the_odometer(1000)
>>>
bike2.reading_odometer()
You can make further experiments with the odometer method. A major
bike3 = Bike('F 900 XR', 'BMW', 'blue', 2014) problem in a showroom is keeping tabs on who is reversing the odometer of
print([Link]()) the motorbikes. If you are a true businessman, you will not like to dupe your
customers. However, sometimes it is not that you who want to dupe the
bike3.updating_the_odometer(700) customers. It is your employees who are trying to bag extra profit in addition
bike3.reading_odometer() to their commission. You must stop this practice if you want to live up to
your customers' expectations and keep your reputation intact. You can add
bike4 = Bike('R 1250 RT', 'BMW', 'brown', 2016) some logic to your program to ensure no rolling back of the odometer by
print([Link]()) anyone. I will integrate an if-else statement to the Bike class and do a few
changes to make it possible.
bike4.reading_odometer()
bike5 = Bike('Heritage Classic', 'Harley Davidson', 'black', 2018) class Bike():
"""This class will build the model of a bike."""
print([Link]())
bike5.reading_odometer() def __init__(self, bmodel, bmake, bcolor, byear):
= RESTART: C:/Users/saifia computers/Desktop/[Link]
We Have A Bike That Hit The Markets In 2012. The Model Is Cg-125. The [Link] = bmodel
Bike Is Manufactured By Honda. Its Color Is Blue. [Link] = bmake
This bike has 100 kilometers on the road. [Link] = bcolor
We Have A Bike That Hit The Markets In 2014. The Model Is F 900 R. The [Link] = byear
Bike Is Manufactured By BMW. Its Color Is Black.
self.odometer_reading = 0
This bike has 1000 kilometers on the road.
def fullname(self):
We Have A Bike That Hit The Markets In 2014. The Model Is F 900 Xr. The
fullbikename = "We have a bike that hit the markets in " +
Bike Is Manufactured By BMW. Its Color Is Blue.
str([Link]) + ". The model is " + [Link] + ". The bike is
This bike has 700 kilometers on the road. manufactured by " + [Link] + ". Its color is " + [Link] + "."
return [Link]() bike4.reading_odometer()
def reading_odometer(self): bike5 = Bike('Heritage Classic', 'Harley Davidson', 'black', 2018)
print("This bike has run " + str(self.odometer_reading) + " kilometers print([Link]())
on the road.")
bike5.updating_the_odometer(0)
def updating_the_odometer(self, bmileage): bike5.reading_odometer()
self.odometer_reading = bmileage = RESTART: C:/Users/saifia computers/Desktop/[Link]
if bmileage >= self.odometer_reading: We Have A Bike That Hit The Markets In 2012. The Model Is Cg-125. The
self.odometer_reading = bmileage Bike Is Manufactured By Honda. Its Color Is Blue.
else: This bike has run 100 kilometers on the road.
print("You are not authorized to roll back the reading of the We Have A Bike That Hit The Markets In 2014. The Model Is F 900 R. The
odometer.") Bike Is Manufactured By BMW. Its Color Is Black.
This bike has run 1000 kilometers on the road.
bike1 = Bike('CG-125', 'Honda', 'blue', 2012)
We Have A Bike That Hit The Markets In 2014. The Model Is F 900 Xr. The
print([Link]()) Bike Is Manufactured By BMW. Its Color Is Blue.
bike1.updating_the_odometer(100) This bike has run 700 kilometers on the road.
bike1.reading_odometer() We Have A Bike That Hit The Markets In 2016. The Model Is R 1250 Rt.
bike2 = Bike('F 900 R', 'BMW', 'black', 2014) The Bike Is Manufactured By BMW. Its Color Is Brown.
print([Link]()) This bike has run 40 kilometers on the road.
bike2.updating_the_odometer(1000) We Have A Bike That Hit The Markets In 2018. The Model Is Heritage
Classic. The Bike Is Manufactured By Harley Davidson. Its Color Is Black.
bike2.reading_odometer()
This bike has run 0 kilometers on the road.
bike3 = Bike('F 900 XR', 'BMW', 'blue', 2014)
>>>
print([Link]())
You can increase the value of an attribute by introducing a simple method to
bike3.updating_the_odometer(700) the program. I will another method to the class to make it work. I will add
bike3.reading_odometer() incremental values to each of the five instances I have created. The method
will tell Python to add up the incremental value to the existing value and run
bike4 = Bike('R 1250 RT', 'BMW', 'brown', 2016)
the program. The incremented value will be displayed in a separate print
print([Link]()) statement in the code.
bike4.updating_the_odometer(40) class Bike():
"""This class will build the model of a bike.""" bike1.updating_the_odometer(100)
bike1.reading_odometer()
def __init__(self, bmodel, bmake, bcolor, byear):
bike1.incrementing_odometer(1000)
[Link] = bmodel bike1.reading_odometer()
[Link] = bmake bike2 = Bike('F 900 R', 'BMW', 'black', 2014)
[Link] = bcolor print([Link]())
[Link] = byear bike2.updating_the_odometer(1000)
self.odometer_reading = 0 bike2.reading_odometer()
def fullname(self): bike2.incrementing_odometer(500)
fullbikename = "We have a bike that hit the markets in " + bike2.reading_odometer()
str([Link]) + ". The model is " + [Link] + ". The bike is bike3 = Bike('F 900 XR', 'BMW', 'blue', 2014)
manufactured by " + [Link] + ". Its color is " + [Link] + "."
print([Link]())
return [Link]()
bike3.updating_the_odometer(700)
def reading_odometer(self):
bike3.reading_odometer()
print("This bike has run " + str(self.odometer_reading) + " kilometers
on the road.") bike3.incrementing_odometer(1000)
def updating_the_odometer(self, bmileage): bike3.reading_odometer()
self.odometer_reading = bmileage bike4 = Bike('R 1250 RT', 'BMW', 'brown', 2016)
if bmileage >= self.odometer_reading: print([Link]())
self.odometer_reading = bmileage bike4.updating_the_odometer(40)
else: bike4.reading_odometer()
print("You are not authorized to roll back the reading of the bike4.incrementing_odometer(1000)
odometer.") bike4.reading_odometer()
def incrementing_odometer(self, bmileage): bike5 = Bike('Heritage Classic', 'Harley Davidson', 'black', 2018)
self.odometer_reading += bmileage print([Link]())
bike5.updating_the_odometer(0)
bike1 = Bike('CG-125', 'Honda', 'blue', 2012)
bike5.reading_odometer()
print([Link]())
bike5.incrementing_odometer(10000) Chapter Nine: The Inheritance Class
bike5.reading_odometer()
= RESTART: C:/Users/saifia computers/Desktop/[Link] Now that you have learned how to write a class, it is pertinent to mention that
Python classes are well known for the ease of use they offer to programmers.
We Have A Bike That Hit The Markets In 2012. The Model Is Cg-125. The Once you have written a class, you can reuse it multiple times. There is a
Bike Is Manufactured By Honda. Its Color Is Blue. process called inheritance in which a subclass is inherited from the parent
This bike has run 100 kilometers on the road. class. The inherited class is named that way because it inherits the attributes
of the parent class. The inherited class is dubbed as the child class. It can use
This bike has run 1100 kilometers on the road.
each attribute and method of the parent class. However, you also can create
We Have A Bike That Hit The Markets In 2014. The Model Is F 900 R. The new attributes only for the child class.
Bike Is Manufactured By BMW. Its Color Is Black.
Just as you did for the parent class, you will also have to use the __init__()
This bike has run 1000 kilometers on the road. method for the child class. I will create a child class of racer bikes.
This bike has run 1500 kilometers on the road. class Bike():
We Have A Bike That Hit The Markets In 2014. The Model Is F 900 Xr. The """This class will build the model of a bike."""
Bike Is Manufactured By BMW. Its Color Is Blue.
This bike has run 700 kilometers on the road. def __init__(self, bmodel, bmake, bcolor, byear):
This bike has run 1700 kilometers on the road.
[Link] = bmodel
We Have A Bike That Hit The Markets In 2016. The Model Is R 1250 Rt.
The Bike Is Manufactured By BMW. Its Color Is Brown. [Link] = bmake

This bike has run 40 kilometers on the road. [Link] = bcolor

This bike has run 1040 kilometers on the road. [Link] = byear

We Have A Bike That Hit The Markets In 2018. The Model Is Heritage self.odometer_reading = 0
Classic. The Bike Is Manufactured By Harley Davidson. Its Color Is Black. def fullname(self):
This bike has run 0 kilometers on the road. fullbikename = "We have a bike that hit the markets in " +
This bike has run 10000 kilometers on the road. str([Link]) + ". The model is " + [Link] + ". The bike is
manufactured by " + [Link] + ". Its color is " + [Link] + "."
>>>
return [Link]()
def reading_odometer(self):
print("This bike has run " + str(self.odometer_reading) + " kilometers
on the road.")
def updating_the_odometer(self, bmileage): keep the child class inside the parent class. The name of the child class must
self.odometer_reading = bmileage include parenthesis that carry the name of the parent class. I have added one
additional function, the super function that aids Python in forming
if bmileage >= self.odometer_reading: connections between the child class and the parent class. The child class has
self.odometer_reading = bmileage taken all the attributes of the parent class. I have not yet added any special
attribute to the racer bike.
else:
Child Class in Python 2.7
print("You are not authorized to roll back the reading of the
odometer.") If you are using Python 2.7, the child class will appear to be a bit different.
See the following code and note the difference.
def incrementing_odometer(self, bmileage):
class Bike():
self.odometer_reading += bmileage
"""This class will build the model of a bike."""
class RacerBike(Bike):
def __init__(self, bmodel, bmake, bcolor, byear):
def __init__(self, bmodel, bmake, bcolor, byear):
super().__init__(bmodel, bmake, bcolor, byear) [Link] = bmodel
racer1 = RacerBike('URS: Gravel Riding', 'BMC', 'Grey', '2017') [Link] = bmake
print([Link]()) [Link] = bcolor
racer2 = RacerBike('Trackmachine', 'BMC', 'Blue', '2015') [Link] = byear
print([Link]()) self.odometer_reading = 0
racer3 = RacerBike('Alpenchallenge', 'BMC', 'Red', '2012') def fullname(self):
print([Link]()) fullbikename = "We have a bike that hit the markets in " +
= RESTART: C:/Users/saifia computers/Desktop/[Link] str([Link]) + ". The model is " + [Link] + ". The bike is
manufactured by " + [Link] + ". Its color is " + [Link] + "."
We Have A Bike That Hit The Markets In 2017. The Model Is Urs: Gravel
Riding. The Bike Is Manufactured By Bmc. Its Color Is Grey. return [Link]()

We Have A Bike That Hit The Markets In 2015. The Model Is def reading_odometer(self):
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue. print("This bike has run " + str(self.odometer_reading) + " kilometers
We Have A Bike That Hit The Markets In 2015. The Model Is on the road.")
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue. def updating_the_odometer(self, bmileage):
>>> self.odometer_reading = bmileage
The most important thing to keep in mind while creating a child class is to if bmileage >= self.odometer_reading:
self.odometer_reading = bmileage Child Class Attributes
else: Once the child class inherits the parent class's attributes, you can go on to add
to it new methods and attributes. I will use the same program and add new
print("You are not authorized to roll back the reading of the
odometer.") attributes for the child class.

def incrementing_odometer(self, bmileage): class Bike():

self.odometer_reading += bmileage """This class will build the model of a bike."""

class RacerBike(Bike): def __init__(self, bmodel, bmake, bcolor, byear):

def __init__(self, bmodel, bmake, bcolor, byear): [Link] = bmodel


super(RacerBike,self).__init__(bmodel, bmake, bcolor, byear) [Link] = bmake
racer1 = RacerBike('URS: Gravel Riding', 'BMC', 'Grey', '2017') [Link] = bcolor
print([Link]()) [Link] = byear
racer2 = RacerBike('Trackmachine', 'BMC', 'Blue', '2015') self.odometer_reading = 0
print([Link]()) def fullname(self):
racer3 = RacerBike('Alpenchallenge', 'BMC', 'Red', '2012') fullbikename = "We have a bike that hit the markets in " +
print([Link]()) str([Link]) + ". The model is " + [Link] + ". The bike is
manufactured by " + [Link] + ". Its color is " + [Link] + "."
The only change I made was in the super function. I filled in the parenthesis
with the name of the child class and self-parameter. An interesting thing is return [Link]()
that this change does not affect the result of the program, no matter if you do def reading_odometer(self):
it in Python 3 or 2.7. However, the former technique will not work in 2.7.
You can see the result of the program as under: print("This bike has run " + str(self.odometer_reading) + " kilometers
on the road.")
= RESTART: C:/Users/saifia computers/Desktop/[Link]
def updating_the_odometer(self, bmileage):
We Have A Bike That Hit The Markets In 2017. The Model Is Urs: Gravel
Riding. The Bike Is Manufactured By Bmc. Its Color Is Grey. self.odometer_reading = bmileage
We Have A Bike That Hit The Markets In 2015. The Model Is if bmileage >= self.odometer_reading:
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue. self.odometer_reading = bmileage
We Have A Bike That Hit The Markets In 2015. The Model Is else:
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue.
print("You are not authorized to roll back the reading of the
>>> odometer.")
def incrementing_odometer(self, bmileage): This racer bike has three textile layered performance tires.
self.odometer_reading += bmileage >>>
In the next code snippet, I will add another attribute to the child class. This
class RacerBike(Bike): attribute shows why a racer bike has a higher rate of aerodynamic efficiency.
def __init__(self, bmodel, bmake, bcolor, byear): class Bike():
super(RacerBike,self).__init__(bmodel, bmake, bcolor, byear) """This class will build the model of a bike."""
self.performance_tire = 'three textile layered'
def describe_tires(self): def __init__(self, bmodel, bmake, bcolor, byear):

print("This racer bike has " + self.performance_tire + " performance [Link] = bmodel
tires.")
[Link] = bmake
racer1 = RacerBike('URS: Gravel Riding', 'BMC', 'Grey', '2017')
[Link] = bcolor
print([Link]())
[Link] = byear
racer1.describe_tires()
self.odometer_reading = 0
racer2 = RacerBike('Trackmachine', 'BMC', 'Blue', '2015')
def fullname(self):
print([Link]())
fullbikename = "We have a bike that hit the markets in " +
racer2.describe_tires() str([Link]) + ". The model is " + [Link] + ". The bike is
racer3 = RacerBike('Alpenchallenge', 'BMC', 'Red', '2012') manufactured by " + [Link] + ". Its color is " + [Link] + "."
print([Link]()) return [Link]()
racer3.describe_tires() def reading_odometer(self):
= RESTART: C:/Users/saifia computers/Desktop/[Link] print("This bike has run " + str(self.odometer_reading) + " kilometers
on the road.")
We Have A Bike That Hit The Markets In 2017. The Model Is Urs: Gravel
Riding. The Bike Is Manufactured By Bmc. Its Color Is Grey. def updating_the_odometer(self, bmileage):
This racer bike has three textile layered performance tires. self.odometer_reading = bmileage
We Have A Bike That Hit The Markets In 2015. The Model Is if bmileage >= self.odometer_reading:
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue. self.odometer_reading = bmileage
This racer bike has three textile layered performance tires. else:
We Have A Bike That Hit The Markets In 2015. The Model Is print("You are not authorized to roll back the reading of the
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue. odometer.")
def incrementing_odometer(self, bmileage): We Have A Bike That Hit The Markets In 2017. The Model Is Urs: Gravel
Riding. The Bike Is Manufactured By Bmc. Its Color Is Grey.
self.odometer_reading += bmileage
This racer bike has three textile layered performance tires.
class RacerBike(Bike): This racer bike has better lift/drag ratio for improved aerodynamic efficiency.
def __init__(self, bmodel, bmake, bcolor, byear): We Have A Bike That Hit The Markets In 2015. The Model Is
super(RacerBike,self).__init__(bmodel, bmake, bcolor, byear) Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue.
self.performance_tire = 'three textile layered' This racer bike has three textile layered performance tires.
self.aerodynamic_efficiency = 'better lift/drag ratio' This racer bike has better lift/drag ratio for improved aerodynamic efficiency.
def describe_tires(self): We Have A Bike That Hit The Markets In 2015. The Model Is
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue.
print("This racer bike has " + self.performance_tire + " performance
tires.") This racer bike has three textile layered performance tires.
def describe_aerodynamics(self): This racer bike has better lift/drag ratio for improved aerodynamic efficiency.
print("This racer bike has " + self.aerodynamic_efficiency + " for >>>
improved aerodynamic efficiency.") Overriding Methods from Parent Class
racer1 = RacerBike('URS: Gravel Riding', 'BMC', 'Grey', '2017') You can override methods from the parent class by defining a method with
print([Link]()) the same name as in the parent class. Python will then block the method's
execution from the parent class, allowing the child class to override the
racer1.describe_tires() method.
racer1.describe_aerodynamics() class Bike():
racer2 = RacerBike('Trackmachine', 'BMC', 'Blue', '2015') """This class will build the model of a bike."""
print([Link]())
racer2.describe_tires() def __init__(self, bmodel, bmake, bcolor, byear):

racer2.describe_aerodynamics() [Link] = bmodel


racer3 = RacerBike('Alpenchallenge', 'BMC', 'Red', '2012')
[Link] = bmake
print([Link]())
[Link] = bcolor
racer3.describe_tires()
[Link] = byear
racer3.describe_aerodynamics()
self.odometer_reading = 0
= RESTART: C:/Users/saifia computers/Desktop/[Link]
def fullname(self):
fullbikename = "We have a bike that hit the markets in " + def incrementing_odometer(self, bmileage):
str([Link]) + ". The model is " + [Link] + ". The bike is
print("I cannot increment the odometer.")
manufactured by " + [Link] + ". Its color is " + [Link] + "."
racer1 = RacerBike('URS: Gravel Riding', 'BMC', 'Grey', '2017')
return [Link]()
print([Link]())
def reading_odometer(self):
racer1.describe_tires()
print("This bike has run " + str(self.odometer_reading) + " kilometers
on the road.") racer1.describe_aerodynamics()
def updating_the_odometer(self, bmileage): racer1.reading_odometer()
self.odometer_reading = bmileage racer1.incrementing_odometer(1000)
if bmileage >= self.odometer_reading: racer2 = RacerBike('Trackmachine', 'BMC', 'Blue', '2015')
self.odometer_reading = bmileage print([Link]())
else: racer2.describe_tires()
print("You are not authorized to roll back the reading of the racer2.describe_aerodynamics()
odometer.") racer2.reading_odometer()
def incrementing_odometer(self, bmileage): racer2.incrementing_odometer(1000)
self.odometer_reading += bmileage racer3 = RacerBike('Alpenchallenge', 'BMC', 'Red', '2012')

class RacerBike(Bike): print([Link]())

def __init__(self, bmodel, bmake, bcolor, byear): racer3.describe_tires()


racer3.describe_aerodynamics()
super(RacerBike,self).__init__(bmodel, bmake, bcolor, byear)
racer3.reading_odometer()
self.performance_tire = 'three textile layered'
racer3.incrementing_odometer(5000)
self.aerodynamic_efficiency = 'better lift/drag ratio'
= RESTART: C:/Users/saifia computers/Desktop/[Link]
def describe_tires(self):
>>>
print("This racer bike has " + self.performance_tire + " performance
tires.") We Have A Bike That Hit The Markets In 2017. The Model Is Urs: Gravel
def describe_aerodynamics(self): Riding. The Bike Is Manufactured By Bmc. Its Color Is Grey.
This racer bike has three textile layered performance tires.
print("This racer bike has " + self.aerodynamic_efficiency + " for
improved aerodynamic efficiency.") This racer bike has better lift/drag ratio for improved aerodynamic efficiency.
This bike has run 0 kilometers on the road. def fullname(self):
I cannot increment the odometer. fullbikename = "We have a bike that hit the markets in " +
str([Link]) + ". The model is " + [Link] + ". The bike is
We Have A Bike That Hit The Markets In 2015. The Model Is
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue. manufactured by " + [Link] + ". Its color is " + [Link] + "."

This racer bike has three textile layered performance tires. return [Link]()

This racer bike has better lift/drag ratio for improved aerodynamic efficiency. def reading_odometer(self):
print("This bike has run " + str(self.odometer_reading) + " kilometers
This bike has run 0 kilometers on the road.
on the road.")
I cannot increment the odometer.
def updating_the_odometer(self, bmileage):
We Have A Bike That Hit The Markets In 2015. The Model Is
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue. self.odometer_reading = bmileage

This racer bike has three textile layered performance tires. if bmileage >= self.odometer_reading:

This racer bike has better lift/drag ratio for improved aerodynamic efficiency. self.odometer_reading = bmileage

This bike has run 0 kilometers on the road. else:

I cannot increment the odometer. print("You are not authorized to roll back the reading of the
odometer.")
>>>
def incrementing_odometer(self, bmileage):
An interesting about classes is the flexibility they have to offer. For example,
instead of making the performance tires an attribute, we can turn it into a self.odometer_reading += bmileage
separate class. After that we can add as many instances to this new class as class Performancetires():
we want to. def __init__(self, performance_tire= 'three textile layered'):
class Bike(): self.performance_tire = performance_tire
"""This class will build the model of a bike.""" def describe_performancetires(self):

def __init__(self, bmodel, bmake, bcolor, byear): print("This racer bike has " + self.performance_tire + " performance
tires.")
[Link] = bmodel
class RacerBike(Bike):
[Link] = bmake
def __init__(self, bmodel, bmake, bcolor, byear):
[Link] = bcolor
super(RacerBike,self).__init__(bmodel, bmake, bcolor, byear)
[Link] = byear
[Link] = Performancetires()
self.odometer_reading = 0
self.aerodynamic_efficiency = 'better lift/drag ratio' This racer bike has better lift/drag ratio for improved aerodynamic efficiency.
def describe_aerodynamics(self): This bike has run 0 kilometers on the road.
print("This racer bike has " + self.aerodynamic_efficiency + " for I cannot increment the odometer.
improved aerodynamic efficiency.")
This racer bike has three textile layered performance tires.
def incrementing_odometer(self, bmileage): We Have A Bike That Hit The Markets In 2015. The Model Is
print("I cannot increment the odometer.") Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue.
racer1 = RacerBike('URS: Gravel Riding', 'BMC', 'Grey', '2017') This racer bike has better lift/drag ratio for improved aerodynamic efficiency.
print([Link]()) This bike has run 0 kilometers on the road.
racer1.describe_aerodynamics() I cannot increment the odometer.
racer1.reading_odometer() This racer bike has three textile layered performance tires.
racer1.incrementing_odometer(1000) We Have A Bike That Hit The Markets In 2015. The Model Is
[Link].describe_performancetires() Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue.
This racer bike has better lift/drag ratio for improved aerodynamic efficiency.
racer2 = RacerBike('Trackmachine', 'BMC', 'Blue', '2015')
print([Link]()) This bike has run 0 kilometers on the road.

racer2.describe_aerodynamics() I cannot increment the odometer.

racer2.reading_odometer() This racer bike has three textile layered performance tires.

racer2.incrementing_odometer(1000) >>>

[Link].describe_performancetires()
racer3 = RacerBike('Alpenchallenge', 'BMC', 'Red', '2012')
print([Link]())
racer3.describe_aerodynamics()
racer3.reading_odometer()
racer3.incrementing_odometer(5000)
[Link].describe_performancetires()
= RESTART: C:/Users/saifia computers/Desktop/[Link]
We Have A Bike That Hit The Markets In 2017. The Model Is Urs: Gravel
Riding. The Bike Is Manufactured By Bmc. Its Color Is Grey.
Chapter Ten: Importing Classes print("You are not authorized to roll back the reading of the
odometer.")
You can create a module of Python classes and use it later on to create def incrementing_odometer(self, bmileage):
different programs. When you save a Python program with the extension .py, self.odometer_reading += bmileage
it becomes a Python module. I have saved it with a proper file name. I will
now open a new file, name it as [Link] and save the following code. class Performancetires():

class Bike(): def __init__(self, performance_tire= 'three textile layered'):

"""This class will build the model of a bike.""" self.performance_tire = performance_tire


def describe_performancetires(self):
def __init__(self, bmodel, bmake, bcolor, byear): print("This racer bike has " + self.performance_tire + " performance
tires.")
[Link] = bmodel
[Link] = bmake class RacerBike(Bike):
[Link] = bcolor def __init__(self, bmodel, bmake, bcolor, byear):
[Link] = byear super(RacerBike,self).__init__(bmodel, bmake, bcolor, byear)
self.odometer_reading = 0 [Link] = Performancetires()
def fullname(self): self.aerodynamic_efficiency = 'better lift/drag ratio'
fullbikename = "We have a bike that hit the markets in " + def describe_aerodynamics(self):
str([Link]) + ". The model is " + [Link] + ". The bike is print("This racer bike has " + self.aerodynamic_efficiency + " for
manufactured by " + [Link] + ". Its color is " + [Link] + "." improved aerodynamic efficiency.")
return [Link]() def incrementing_odometer(self, bmileage):
def reading_odometer(self): print("I cannot increment the odometer.")
print("This bike has run " + str(self.odometer_reading) + " kilometers Importing Multiple Classes
on the road.")
I have saved the file and closed it. Now I will open a new file and name it
def updating_the_odometer(self, bmileage): my_bike.py. I’ll save it in the same location where I have saved [Link]. For
self.odometer_reading = bmileage example, in my case I have saved both on my desktop to access them easily.
Whatever the location is, it should be the same for the two files or the code
if bmileage >= self.odometer_reading:
will not work in the way you have foreseen it. Now that the file my_bike has
self.odometer_reading = bmileage been saved. I will now write the code in it to import the code from the file
else: [Link].
from bike import Bike I cannot increment the odometer.
from bike import Performancetires This racer bike has three textile layered performance tires.
from bike import RacerBike We Have A Bike That Hit The Markets In 2015. The Model Is
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue.
racer1 = RacerBike('URS: Gravel Riding', 'BMC', 'Grey', '2017')
print([Link]()) This racer bike has better lift/drag ratio for improved aerodynamic efficiency.

racer1.describe_aerodynamics() This bike has run 0 kilometers on the road.

racer1.reading_odometer() I cannot increment the odometer.


This racer bike has three textile layered performance tires.
racer1.incrementing_odometer(1000)
We Have A Bike That Hit The Markets In 2015. The Model Is
[Link].describe_performancetires()
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue.
racer2 = RacerBike('Trackmachine', 'BMC', 'Blue', '2015')
This racer bike has better lift/drag ratio for improved aerodynamic efficiency.
print([Link]())
This bike has run 0 kilometers on the road.
racer2.describe_aerodynamics()
I cannot increment the odometer.
racer2.reading_odometer()
This racer bike has three textile layered performance tires.
racer2.incrementing_odometer(1000)
>>>
[Link].describe_performancetires()
As all the three classes were written in the file [Link], I have imported all of
racer3 = RacerBike('Alpenchallenge', 'BMC', 'Red', '2012') them in a sequence. As there are three classes stored in a single module, if
print([Link]()) you try to import only one of them, you will see an error in the interpreter.
The error will be like this.
racer3.describe_aerodynamics()
from bike import Bike
racer3.reading_odometer()
racer1 = RacerBike('URS: Gravel Riding', 'BMC', 'Grey', '2017')
racer3.incrementing_odometer(5000)
print([Link]())
[Link].describe_performancetires()
racer1.describe_aerodynamics()
>>>= RESTART: C:/Users/saifia computers/Desktop/my_bike.py
racer1.reading_odometer()
We Have A Bike That Hit The Markets In 2017. The Model Is Urs: Gravel
Riding. The Bike Is Manufactured By Bmc. Its Color Is Grey. racer1.incrementing_odometer(1000)
This racer bike has better lift/drag ratio for improved aerodynamic efficiency. [Link].describe_performancetires()
This bike has run 0 kilometers on the road. racer2 = RacerBike('Trackmachine', 'BMC', 'Blue', '2015')
print([Link]())
racer2.describe_aerodynamics() Riding. The Bike Is Manufactured By Bmc. Its Color Is Grey.
racer2.reading_odometer() We Have A Bike That Hit The Markets In 2015. The Model Is
racer2.incrementing_odometer(1000) Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue.

[Link].describe_performancetires() We Have A Bike That Hit The Markets In 2015. The Model Is
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue.
racer3 = RacerBike('Alpenchallenge', 'BMC', 'Red', '2012')
>>>
print([Link]())
Importing Module
racer3.describe_aerodynamics()
You also have an option to import a complete module and then access all the
racer3.reading_odometer() classes in it. This is the simplest and the easiest of the methods to execute a
racer3.incrementing_odometer(5000) program.
[Link].describe_performancetires() import bike
= RESTART: C:/Users/saifia computers/Desktop/my_bike.py racer1 = [Link]('URS: Gravel Riding', 'BMC', 'Grey',
'2017')
Traceback (most recent call last):
print([Link]())
File "C:/Users/saifia computers/Desktop/my_bike.py", line 3, in <module>
racer1.describe_aerodynamics()
racer1 = RacerBike('URS: Gravel Riding', 'BMC', 'Grey', '2017')
racer1.reading_odometer()
NameError: name 'RacerBike' is not defined
racer1.incrementing_odometer(1000)
>>>
[Link].describe_performancetires()
However, if you save a single class in one module, you can correct this error.
racer2 = [Link]('Trackmachine', 'BMC', 'Blue', '2015')
from bike import Bike
print([Link]())
racer1 = Bike('URS: Gravel Riding', 'BMC', 'Grey', '2017')
racer2.describe_aerodynamics()
print([Link]())
racer2.reading_odometer()
racer2 = Bike('Trackmachine', 'BMC', 'Blue', '2015')
racer2.incrementing_odometer(1000)
print([Link]())
[Link].describe_performancetires()
racer3 = Bike('Alpenchallenge', 'BMC', 'Red', '2012')
racer3 = [Link]('Alpenchallenge', 'BMC', 'Red', '2012')
print([Link]())
print([Link]())
= RESTART: C:/Users/saifia computers/Desktop/my_bike.py
racer3.describe_aerodynamics()
We Have A Bike That Hit The Markets In 2017. The Model Is Urs: Gravel
racer3.reading_odometer()
racer3.incrementing_odometer(5000) print([Link]())
[Link].describe_performancetires() racer1.describe_aerodynamics()
= RESTART: C:/Users/saifia computers/Desktop/my_bike.py racer1.reading_odometer()
We Have A Bike That Hit The Markets In 2017. The Model Is Urs: Gravel racer1.incrementing_odometer(1000)
Riding. The Bike Is Manufactured By Bmc. Its Color Is Grey. [Link].describe_performancetires()
This racer bike has better lift/drag ratio for improved aerodynamic efficiency. racer2 = RacerBike('Trackmachine', 'BMC', 'Blue', '2015')
This bike has run 0 kilometers on the road. print([Link]())
I cannot increment the odometer.
racer2.describe_aerodynamics()
This racer bike has three textile layered performance tires.
racer2.reading_odometer()
We Have A Bike That Hit The Markets In 2015. The Model Is
racer2.incrementing_odometer(1000)
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue.
[Link].describe_performancetires()
This racer bike has better lift/drag ratio for improved aerodynamic efficiency.
racer3 = RacerBike('Alpenchallenge', 'BMC', 'Red', '2012')
This bike has run 0 kilometers on the road.
print([Link]())
I cannot increment the odometer.
racer3.describe_aerodynamics()
This racer bike has three textile layered performance tires.
racer3.reading_odometer()
We Have A Bike That Hit The Markets In 2015. The Model Is
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue. racer3.incrementing_odometer(5000)
This racer bike has better lift/drag ratio for improved aerodynamic efficiency. [Link].describe_performancetires()
This bike has run 0 kilometers on the road. = RESTART: C:/Users/saifia computers/Desktop/my_bike.py
I cannot increment the odometer. We Have A Bike That Hit The Markets In 2017. The Model Is Urs: Gravel
Riding. The Bike Is Manufactured By Bmc. Its Color Is Grey.
This racer bike has three textile layered performance tires.
This racer bike has better lift/drag ratio for improved aerodynamic efficiency.
>>>
This bike has run 0 kilometers on the road.
Importing All Classes
I cannot increment the odometer.
There is a trick to import all classes at once.
This racer bike has three textile layered performance tires.
from bike import *
We Have A Bike That Hit The Markets In 2015. The Model Is
racer1 = RacerBike('URS: Gravel Riding', 'BMC', 'Grey', '2017') Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue.
This racer bike has better lift/drag ratio for improved aerodynamic efficiency.
This bike has run 0 kilometers on the road. Conclusion
I cannot increment the odometer.
This racer bike has three textile layered performance tires. Now that you have made it to the end of the book, I hope you have
understood each concept of Python coding to the hilt. I hope that you have
We Have A Bike That Hit The Markets In 2015. The Model Is practiced each code very well and have also digested it well.
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue.
The next step is to keep practicing the codes that I have given and explained
This racer bike has better lift/drag ratio for improved aerodynamic efficiency. the book. Python coding is easier compared to other programming languages.
This bike has run 0 kilometers on the road. The editor is quite helpful as the multiple colors in it guide you through the
codes. The most interesting feature of Python is the display of errors. Each
I cannot increment the odometer.
error carries in it its solution as well as it indicates you where the problem
This racer bike has three textile layered performance tires. lies. You can track the error, rectify it, and run the program again.
>>> You have learned from the basics like datatypes to the advanced stages like
object-oriented programming. All the concepts were explained with due
depth so that when you have gone through them, you are well-versed in
executing them yourself.
Coding knowledge is likely to slip off your mind right after you finish the
book. Therefore, the best method to retain this knowledge is to keep
practicing, creating new programs. You will start enjoying it finally. Python
is the best language if you are interested in automation, machine learning,
and deep learning models. You can use it to be a master of artificial
intelligence systems and data mining systems.
References
[Link]

You might also like