Python-3 Coding 165pgs
Python-3 Coding 165pgs
print(info) print(a)
Hi, 9
5
I
want 18
to 3.0
in the 11390625
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
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']
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', 'computer system'] c_officeitems = officeitems
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.
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']
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)
user = {'uname': username, 'gender': gender, 'email address': email_id} newuser = user_info('Johnson', 'johnson@[Link]', 'male', age=55)
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)
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."""
"""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 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.
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>
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()
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 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.
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):
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
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.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():
[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]