Programming Languages Academy - Python For Beginners - The Biggest Python Programming Crash Course For Beginners-Programming Languages Academy (2023)
Programming Languages Academy - Python For Beginners - The Biggest Python Programming Crash Course For Beginners-Programming Languages Academy (2023)
for Beginners
PROGRAMMING LANGUAGES
ACADEMY
© Copyright 2019 - Programming Languages Academy - All rights
reserved.
The content contained within this book may not be reproduced, duplicated,
or transmitted without direct written permission from the author or the
publisher.
Legal Notice:
This book is copyright protected. It is only for personal use. You cannot
amend, distribute, sell, use, quote, or paraphrase any part, or the content
within this book, without the consent of the author or publisher.
Disclaimer Notice:
Please note the information contained within this document is for
educational and entertainment purposes only. All effort has been executed
to present accurate, up-to-date, reliable, and complete information. No
warranties of any kind are declared or implied. Readers acknowledge that
the author is not engaging in the rendering of legal, financial, medical, or
professional advice. The content within this book has been derived from
various sources. Please consult a licensed professional before attempting
any techniques outlined in this book.
“Wait. Did you not say I don’t need to know anything about programming?”
Well, yes! You do not have to worry about programming or their concepts at
the moment, and when the time comes, I will do my best to explain those.
What is needed of you is something a little more obvious.
● Computer: Like I said, obvious! You need a machine of your own to
download and practice the material and matter you learn from here.
To make the most out of the book, practice as you read. This greatly
increases your confidence and allows you to keep a steady pace.
The specifications do not matter much. Most modern machines
(2012 and above) should be able to run each of the components
without posing any problem.
● An internet connection: You will be required to download a few files
from the internet.
● An Integrated Development Environment (IDE): If, for some reason,
you felt intimidated by this terminology, relax! I will be guiding
you through each and every step to ensure you have all of these and
know what they are all about. For now, just imagine this as a text
editor.
● A fresh mind: There is no point in learning if your mind is not there
with you. Be fresh, be comfortable. This may take a little practice
and a little time, but it will all be worth it.
That is quite literally all that you need. Before we go on into our very first
chapter of the book and start learning the essentials, there is but one more
thing I would like to clarify right away.
Before the inception of Python and the famous language that it has gone on
to become, things were quite different. Imagine a world where programmers
gathered from across the globe in a huge computer lab. You have some of
the finest minds on the planet working together towards a common goal,
whatever that might be. Naturally, even the finest intellectuals can end up
making mistakes.
Suppose one such programmer ended up creating a program, and he is not
too sure of what went wrong. The room is full of other programmers, and
sure enough, approaching someone for assistance would be the first thought
of the day. The programmer approaches another busy person who gladly
decides to help out a fellow intellectual programmer. Within that brief walk
from one station to the other, the programmer quickly exchanges the
information, which seems to be a common error. It is only when the
programmer views the code that they are caught off-guard. This fellow
member has no idea what any of the code does. The variables are labeled
with what can only be defined as encryptions. The words do not make any
sense, nor is there any way to find out where the error lies.
The compiler continues to throw in error after error. Remember, this was
well before 1991 when people did not have IDEs, which would help them
see where the error was and what needed to be done. The entire exercise
would end up wasting hours upon hours just to figure out that a semi-colon
was missing. Embarrassing and absolutely time-wasting!
This was just a small example; imagine the entire thing but on a global
scale. The programming community struggled to find ways to write codes
that could be understood easily by others. Some languages supported some
syntaxes, while others did not. These languages would not necessarily work
in harmony with each other, either. The world of programming was a mess.
Had Python not come at the opportune moment that it did, things would
have been so much more difficult for us to handle.
Guido Van Rossum, a Dutch programmer, decided to work on a pet project.
Yes, you read that, right? Mr. Van Rossum wanted to keep himself occupied
during the holiday season and, hence, decided to write a new interpreter for
a language he had been thinking of lately. He decided to call the language
Python, and contrary to popular belief, it has nothing to do with the reptile
itself. Tracing its root from its predecessor, the ABC, Python came into
existence just when it was needed.
For our non-programming friends, ABC is the name of an old programming
language. Funny as it may sound, naming conventions weren't exactly the
strongest here.
Python was quickly accepted by the programming community, albeit there
is the fact that programmers were a lot less numerous back then. Its
revolutionary user-friendliness, responsive nature, and adaptability
immediately caught the attention of everyone around. The more people
vested their time into this new language, the more Mr. Van Rossum started
investing his resources and knowledge to enhance the experience further.
Within a short span of time, Python was competing against the then leading
languages of the world. It soon went on to outlive quite a few of them
owing to the core concept brought to the table: ease of readability. Unlike
any other programming language of that time, Python delivered codes that
were phenomenally easy to read and understand right away.
Remember our friend, the programmer, who asked for assistance? If he
were to do that now, the other fellow would immediately understand what
was going on.
Python also acquired fame for being a language that had an object-oriented
approach. This opened more usability of the language to the programmers
who required an effective way to manipulate objects. Think of a simple
game. Anything you see within it is an object that behaves in a certain way.
Giving that object that ‘sense’ is object-oriented programming (OOP).
Python was able to pull that off rather easily. Python is considered a multi-
paradigm language, with OOP being a part of that as well.
Fast forward to the world we live in, and Python continues to dominate
some of the cutting-edge technologies in existence. With real-world
applications and a goliath of a contribution to aspects like machine learning,
data sciences, and analytics, Python is leading the charge with full force.
An entire community of programmers has dedicated their careers to
maintaining Python and developing it as time goes by. As for the founder,
Mr. Van Rossum initially accepted the title of Benevolent Dictator for Life
(BDFL) and retired on 12 July 2018. This title was bestowed upon Mr. Van
Rossum by the Python community.
Today, Python 3 is the leading version of the language alongside Python 2,
which has its days numbered. You do not need to learn both of these in
order to succeed. We will begin with the latest version of Python as almost
everything that was involved in the previous version was carried forward,
with the exception of components that were either dull or useless.
I know, right about now, you are rather eager to dive into the concepts and
get done with history. It is vital for us to learn a few things about the
language and why it came into existence in the first place. This information
might be useful at some point in time, especially if you were to look at
various codes and identify which one of those was written in Python and
which one was not.
For anyone who may have used languages like C, C++, C#, or JavaScript,
you might find quite a few similarities within Python and some major
improvements too. Unlike in most of these languages, where you need to
use a semicolon to let the compiler know that the line has ended, Python
needs none of that. Just press enter, and the program immediately
understands that the line has ended.
Before we do jump ahead, remember how some skeptics would have you
believe it is too late to learn Python? It is because of Python that self-
driving cars are coming into existence. Has the world seen too much of
them already? When was the last time you saw one of these vehicles on the
road? This is just one of a gazillion possibilities that lay ahead for us to
conquer. All it needs is for us to learn the language, brush up on our skills,
and get started.
“A journey to a thousand miles begins with the first step. After that, you are
already one step closer to your destination.”
Okay, I added that last sentence by myself, but it is only to provide you with
all the confidence you need to learn this language. Most of the things we
will visit within Python would make sense right away as Python main uses
English sentences and allows for greater ease when it comes to readability.
However, there is no reason why you should rush into things. Take your
time and practice as much as you can using the exercise book, only after
you have learned something through this book. While you can always read
through the book from end to end, it is advisable to practice these codes as
you learn them.
Last-Minute Tips
You have made it thus far and have learned all there is to, or at least all the
important history bits. The time has come for us to start our journey and
start typing some lines which, initially, might not make sense, but soon will
start to, and you will certainly enjoy the journey. To make the most of the
journey, here are a few things you need to ensure:
● While it is encouraged to practice as you read, it is highly unlikely
that you will need to type in exactly the same code every time. It is,
therefore, important to start playing with the code a little once you
get the hang of things. This also increases your confidence and
allows you to create your own unique programs. If you see me
using a variable called name and I have assigned it a value of
‘Sam,’ feel free to change that to your own name. Change the
numbers where and when possible to see how it changes the results.
● It is very much important for you to remain up to date with the latest
version of Python. We will be looking into a bit about how to find
the latest version of Python, and once we do, keep checking the
official Python website to see if a new version has arrived.
● Do not be bogged down with problems as you will encounter quite a
lot of them. I will deliberately place a few hurdles to test your
knowledge as well, and I will solve those too. Learning how to
overcome errors and understand them is a significant way to learn
things. Should you encounter an error other than the ones covered
within this book, feel free to seek help from the ever-active
community of Python.
● Practice a few hours a day if you really wish to become a
programmer and pursue a career in Python. It takes a significant
time to master all the codes, the functions, the libraries, and much
more.
● Do not skip chapters – that is a bad idea unless you genuinely know
your way around.
● Do not compare yourself with others. Everyone is born with a
unique mind, and so are you. If one is learning quicker than you, let
them. Learn at a pace you can keep up with.
● Learn from one source at a time. Learning from various sources at
the same time would get you into a state of confusion.
● If you do not understand something, try revisiting the basics or the
previous chapters. You may have missed something back there.
With that said, the time is upon us to commence our journey. Ladies and
gentlemen, start your engines! We are about to embark on a ride of a
lifetime!
Chapter 2
Installing Python
The first order of business is to download the latest version of Python. The
version that is available at the time of writing this book is Python 3.8.0, so
we will be using that. For any future versions, there is a good chance all of
the commands and features will work exactly the same unless the
community decides to change the way the language works radically.
Let us begin by opening up our web browser and going straight to the
source. In the address bar, type in www.python.org, and you will be greeted
by a simplistic website as shown here:
Hover the mouse cursor over ‘Downloads’, and the website should be able
to detect your platform and present the corresponding version accordingly
automatically. Click on the button to commence the download.
If it doesn’t, simply click on the name of the platform you are using to be
taken to the downloads page. Here, click on the first option that says “Latest
Python 3 Release – Python 3.8.0” and download that.
Once the file has been downloaded, simply run it to install Python within
your system. This should not take more than a minute or so. Now run the
command prompt/terminal once again and type in ‘python’ to see the
version of Python installed within your machine. This, therefore, confirms
that the installation went well.
For Linux users, depending on the kind of flavor you are using, you will
need to execute certain commands. Here’s a step-by-step process on how
you can get Python 3.8.0 on your system.
Step 1: Enter the following commands on your terminal.
sudo apt-get install build-essential checkinstall
sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev
libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev libffi-dev zlib1g-
dev
This essentially installs the libraries which are needed to ensure the
successful installation of Python 3.8. If asked to choose Yes or No, choose
Yes and proceed.
Step 2: Once sorted, you will now need to enter the following commands:
Sudo wget https://www.python.org/ftp/python/3.8.0/Python-3.8.0.tgz
This will download the necessary file you need directly to your current
working directory. Once the file is downloaded, you will need to extract it,
and to do so, enter the following command:
sudo tax xzf Python-3.8.0.tgz
Step 3: Now, we will run some codes to install Python using ‘altinstall’,
which is a more secure way of doing things. First, enter the Python-3.8.0
folder by entering the following command:
cd Python-3.8.0
Next, you will need to run these two commands. Please note, that this will
take some considerable time, so do grab a bit of a break if you like.
sudo ./configure –enable-optimization
sudo make altinstall
Step 4: The long, arduous, and extensive installation process has finally
ended. It is time to check the version of Python to verify we have the right
one installed.
Python3.8
And voila! You have yourself the latest version of Python installed on your
machine. Now, we can resume the preparations.
All computer users, regardless of their operating system, are now in line
and have Python up and running. The problem is, no one can find an
application for that. There is a reason for that. We haven’t yet installed that
“Text Editor” we spoke about earlier.
In order for us to run Python and be able to use it to write programs, we
need an integrated development environment (IDE). For Python, we will be
using one of the finest, if not the best, in the business. It is called the
PyCharm, and it is all that you need to get started.
To download PyCharm, browse to https://www.jetbrains.com/pycharm/, and
click on download. On the next screen, click on the community edition, as it
is free, and we aren’t exactly using it for large-scale operation, at least not
yet. The download should start automatically. Once done, open the file to
start the installation process.
Important!
For Windows users, at the start of the installation, you will come across a
screen that gives you multiple options, as shown below. Be sure to check the
“Add Launchers dir to the PATH.” If you do not check this, you may run
into issues later on.
Hmm! You pressed enter, and nothing happened. Well, that’s no fun, is it?
Remember the ‘Run’ menu? Go ahead and click on it and choose, well,
‘Run’ to initiate the program. Another window would pop-up from the
bottom and show this:
"C:\Users\Programmer \AppData\Local\Programs\Python\Python37-
32\python.exe" "C:/Users/Programmer /PycharmProjects/PFB/Test1.py"
I made it!
Process finished with exit code 0
Two things just happened here. First, you may not have realized this, but
you just made your first-ever program. Congratulations are in order! You
just commanded your computer to print out a message of your choice.
Second, this little box that appeared from the bottom is called the console,
and you have just discovered the last piece in the puzzle. The console is
where the information, the program, and the result gets printed.
Now, you have seen everything you need to know to get started. You do not
need to roam around any other options. Even the ‘Run’ menu will no longer
be used, at least not all the time anyway. You now should be able to see the
green play button on the top right corner, next to the little dialog box that
has your program’s name on it. Next time, simply click that, and you should
be able to execute a program.
Craving to type a little more? Go ahead, type the following lines, and have
a blast running these.
print("I made it!")
print("======")
print("If I only knew it would be this easy")
print("======")
print("I would have taken up Python ages ago")
print("======")
Output:
I made it!
======
If I only knew it would be this easy
======
I would have taken up Python ages ago
======
Two programs already? Nice pace! It certainly seems like we are ready to
dive deeper into the world of Python and start learning what exactly things
like the ‘print’ command do, why we use quotation marks, and all that
goodness.
You have installed Python, and you have grabbed your copy of PyCharm as
well. You just created two simple programs that are able to print out
information to the console accordingly to what you type in. We are now
fully operational, ready, and open for business.
Remember, you cannot expect to become an overnight programming
sensation. Programming of any kind takes time to master and develop. You
cannot expect to learn anything new and become a master within a short
span of time. Squeeze some time out from your daily routine. Maybe stop
playing too many games, spending time pointlessly scrolling up and down
on social media sites, or even going out with friends every day. If you put
your heart and soul here for the next year, you will be thanking me for ages
to come.
With that said, let’s take our first step on that journey of a thousand miles.
Scratch that; you already took a few steps. Let’s just continue the
momentum and hope to add a skill to our name that will serve us for times
to come. Let us learn Python.
Chapter 3
Let us begin with the program that we just created in the last chapter. To
remind ourselves what it was, here’s a quick look at the commands we
wrote:
print("I made it!")
print("======")
print("If I only knew it would be this easy")
print("======")
print("I would have taken up Python ages ago")
print("======")
We used a print command to have our message printed at the console box as
our output of the program. Calling ‘print’ a command is technically wrong;
it is a function. While we will be covering functions and methods in detail
later on, for now, just remember that functions are names of commands
which are followed by the parenthesis “()” where the brackets will either be
empty or contain some type of data. There are set parameters that are pre-
defined, meaning that certain functions will only be able to accept a specific
type of data.
In the above example, we used nothing more than text. A few letters to
create a message, and that is it. In Python, things work differently. Text is
not identified as text. We need to tell Python that we want this to be printed
as text. How do we do that? We use single or double quotation marks,
which allows Python to understand that anything within the quotes is text,
and it needs to print it the way it is.
I bet most of you may not have noticed how all of the lines start with a
lowercase ‘p’ instead of the opposite. Ah, yes! Now that you noticed it let
me tell you why we did that.
Python is a case-sensitive language. It considers everything as a character,
not a letter or text. This means that the lowercase ‘p’ will not be the same
character as the uppercase ‘P’ and so on, and so forth.
Print
PRINT
print
PrinT
pRINt
All of these will be treated differently by Python, and for printing purposes,
these will not work at all except for ‘print’ as that is the standard way of
outputting things.
To name anything in Python, we normally use lower cases for one-word
commands. This isn’t something that is exclusive to Python, as every
language uses some way as a standard to write codes. What makes Python
different is the sheer amount of thought that was put into the naming
convention to make code easier to read. Remember this, anything with more
than the word, you can use a few ways to do so as shown here:
last_name
LastName
lastname
LASTNAME
In most of the cases, we will be using the first approach, where each letter
begins with a lowercase. For components with more than one word, we will
be using underscores to separate them. The next in line is generally used
only in cases of classes. At this point in time, you do not have to worry
about what classes are. Just remember those words with the first letter as
capital and that having no underscores is an example of Camel Case and
used for classes.
Next down the line is the way we use to name packages. Here, all the words
begin and end with lowercase letters and have no underscores between
them. On the polar opposite, we have our last entry, which is used to define
constants. Here, all the letters are in uppercase and have no underscores
separating the words.
Boring, wasn’t it? I know! But it is something you may want to remember
as we will be doing quite a lot of these. You should know when to use
which convention, as this greatly improves the code readability. The entire
point of Python is to promote code readability, and if we go against that,
there’s not much point in learning Python.
Now that we have covered this let us start by discussing data types that are
at work within Python. Without these, no programming language would
operate or work. They are what we use as inputs, and these are what direct
the program per our desire accordingly.
Strings
In Python and other programming languages, any text values that we may
use, such as names, places, and sentences, are all referred to as strings. A
string is a collection of characters, not words or letters, which is marked by
the use of single or double quotation marks.
To display a string, use the print command, open up a parenthesis, put in a
quotation mark, and write anything. Once done, we generally end the
quotation marks and close the bracket.
Since we are using PyCharm, IntelliSense detects what we are about to do
and delivers the rest for us immediately. You may have noticed how it
jumped to the rescue when you only typed in the opening bracket. It will
automatically provide you with a closing one. Similarly, for the quotation
marks, one or two, it will provide the closing ones for you. See why we are
using PyCharm? It greatly helps us out.
“I do have a question. Why do we use either single or double quotation
marks if both provide the same result?”
Ah! Quite the eye. There is a reason we use these; let me explain by using
the example below:
print(‘I’m afraid I won’t be able to make it’)
print(“He said “Why do you care?””)
Try and run this through PyCharm. Remember, to run, simply click on the
green play-like button on the top right side of the interface.
"C:\Users\Programmer\AppData\Local\Programs\Python\Python37-
32\python.exe" "C:/Users/Programmer/PycharmProjects/PFB/Test1.py"
File "C:/Users/Programmer/PycharmProjects/PFB/Test1.py", line 1
print('I'm afraid I won't be able to make it')
^
SyntaxError: invalid syntax
Lastly, for strings, the naming convention does not apply to the text of the
string itself. You can use regular English writing methods and conventions
without worries, as long as that is within the quotation marks. Anything
outside it will not be a string in the first place and will or may not work if
you change the cases.
Did you know that strings also use triple quotes? Never heard that before,
have you? We will cover that shortly!
Numeric Data type
Just as the number suggests, Python is able to recognize numbers rather
well. The numbers are divided into two pairs:
● Integer – A positive and/or negative whole numbers that are
represented without any decimal points.
● Float – A real number that has a decimal point representation.
This means, if you were to use 100 and 100.00, one would be identified as
an integer while the other will be deemed as a float. So why do we need to
use two various number representations?
If you are designing a program, suppose a small game that has a character’s
life of 10, you might wish to keep the program in a way that whenever a
said character takes a hit, his life reduces by one or two points. However, to
make things a little more precise, you may need to use float numbers. Now,
each hit might vary and may take 1.5, 2.1, or 1.8 points away from the life
total.
Using floats allows us to use greater precision, especially when calculations
are on the cards. If you aren’t too troubled about the accuracy, or your
programming involves whole numbers only, stick to integers.
Booleans
Ah! The one with the funny name. Boolean (or bool) is a data type that can
only operate on and return two values: True or False. Booleans are a vital
part of any program, except the ones where you may never need them, such
as our first program. These are what allow programs to take various paths if
the result is true or false.
Here’s a little example. Suppose you are traveling to a country you have
never been to. There are two choices you are most likely to face.
If it is cold, you will be packing your winter clothes. If it is warm, you will
be packing clothes which are appropriate for warm weather. Simple, right?
That is exactly how the Booleans work. We will look into the coding aspect
of it as well. For now, just remember, when it comes to true and false, you
are dealing with a bool value.
List
While this is slightly more advanced for someone at this stage of learning,
the list is a data type that does exactly what it sounds like. It lists objects,
values, or stores data within square brackets ([]). Here’s what a list would
look like:
month = ['Jan', 'Feb', 'March', 'And so on!']
We will be looking into this separately, where we will discuss lists, tuples,
and dictionaries.
We have briefly discussed these data types. Surely, they are used within
Python, but how? If you think you can type in the numbers and true and
false, all on their own, it will never work.
Variables
You have the passengers, but you do not have a mode of commuting; they
will have nowhere to go. These passengers would just be folks standing
around, waiting for some kind of transportation to pick them up. Similarly,
data types cannot function alone. They need to be ‘stored’ in these vehicles,
which can take them places. These special vehicles, or as we programmers
refer to as containers, are called ‘variables,’ and they are exactly what
perform the magic for us.
Variables are specialized containers that store a specific value in them and
can then be accessed, called, modified, or even removed when the need
arises. Every variable that you may create will hold a specific type of data
in them. You cannot add more than one type of data within a variable.
In other programming languages, you will find that in order to create a
variable, you need to use the keyword ‘var’ followed by an equals mark ‘=’
and then the value. In Python, it is a lot easier, as shown below:
name = "John"
age = 33
weight = 131.50
is_married = True
In the above, we have created a variable named ‘name’ and given it a value
of characters. If you recall strings, we have used double quotation marks to
let the program know that this is a string.
We then created a variable called age. Here, we simply wrote 33, which is
an integer as there are no decimal figures following that. You do not need to
use quotation marks here at all.
Next, we created a variable ‘weight’ and assigned it a float value.
Finally, we created a variable called ‘is_married’ and assigned it a ‘True’
bool value. If you were to change the ‘T’ to ‘t’ the system will not
recognize it as a bool and will end up giving an error.
Focus on how we used the naming convention for the last variable. We will
be ensuring that our variables follow the same naming convention.
You can even create blank variables in case you feel like you may need
these at a later point in time or wish to initiate them at no value at the start
of the application. For variables with numeric values, you can create a
variable with a name of your choosing and assign it a value of zero.
Alternatively, you can create an empty string as well by using opening and
closing quotation marks only.
empty_variable1 = 0
empty_variable2 = ""
You do not have to name them like this necessarily; you can come up with
more meaningful names so that you and any other programmer who may
read your code would understand. I have given them these names to ensure
anyone can immediately understand their purpose.
Now we have learned how to create variables, let’s learn how to call them.
What’s the point of having these variables if we are never going to use
them, right?
Let’s create a new set of variables. Have a look here:
name = "Jonah"
age = 47
height_in_cm = 170
occupation = "Programmer"
I do encourage you to use your own values and play around with variables
if you like.
In order for us to call the name variable, we simply need to type the name
of the variable. In order to print that to the console, we will do this:
print(name)
Output
Jonah
The same goes for the age, the height variable, and occupation. But what if
we wanted to print them together and not separately?
Try running the code below and see what happens:
print(name age height_in_cm occupation)
Here is the reason why that happened. When you were using a single
variable, the program knew what variable that was. The minute you added a
second, a third, and a fourth variable, it tried to look for something that was
written in that manner. Since there wasn’t any, it returned with an error that
otherwise says:
“Umm… Are you sure, Sir? I tried looking everywhere, but I couldn’t find
this ‘name age height_in_cm occupation’ element anywhere.”
All you need to do is add a comma to act as a separator like so:
print(name, age, height_in_cm, occupation)
Output:
Jonah 47 170 Programmer
To join these two strings into one, we can use the ‘+’ sign. The resulting
string will now be called a String Object, and since this is Python we are
dealing with, everything within this language is considered as an object,
thus the Object-Oriented Programming nature that we discussed somewhere
in the start.
first_name = "John"
last_name = "Wick"
first_name + last_name
Here, we did not ask the program to print the two strings. If you wish to
print these two instead, simply add the print function and type in the string
variables with a + sign in the middle within parentheses. Sounds good, but
the result will not be quite what you expect:
first_name = "John"
last_name = "Wick"
print(first_name + last_name)
Output:
JohnWick
Hmm. Why do you think that happened? Certainly, we did use a space
between the two variables. The problem is that the two strings have
combined together, quite literally here, and we did not provide a white
space (blank space) after John or before Wick; it will not include that. Even
the white space can be a part of a string. To test it out, add one character of
space within the first line of code by tapping on the friendly spacebar after
John. Now try running the same command again, and you should see “John
Wick” as your result.
The process of merging two strings is called concatenation. While you can
concatenate as many strings as you like, you cannot concatenate a string
and an integer together. If you really need to do that, you will need to use
another technique first to convert the integer into a string and then
concatenate the same. To convert an integer, we use the str() function.
text1 = "Zero is equal to "
text2 = 0
print(text1 + str(text2))
Output:
Zero is equal to 0
Python reads the codes in a line-by-line method. First, it will read the first
line, then the second, then third, and so on. This means we can do a few
things beforehand as well, to save some time for ourselves.
text1 = "Zero is still equal to "
text2 = str(0)
print(text1 + text2)
Output:
Zero is still equal to 0
While there are other variations to convert integers into strings and
concatenate strings together, it is best to learn those which are used
throughout the industry as standard.
Remember the triple quotes that I mentioned earlier? I believe you are in a
good position now to begin using those.
Have a look at this result, and keep in mind that I did not use any variable
here at all.
Now, you have seen how to create a variable, recall it, and concatenate the
same. Everything sounds perfect, except for one thing; These are predefined
values. What if we need an input directly from the end-user? How can we
possibly know that? Even if we do, where do we store them?
User-Input Values
Suppose we are trying to create an online form. This form will contain
simple questions like asking for the user’s name, age, city, email address,
and so on. There must be some way through which we can allow users to
input these values on his/her own and for us to get those back. We can use
the same to print out a message that thanks to the user for using the form
and that they will be contacted on their email address for further steps.
To do that, we will use the input() function. The input function can accept
any kind of input. In order to use this function, we will need to provide it
with some reference so that the end-user is able to know what he/she is
about to fill out.
Let us look at a typical example and see how such a form can be created:
print("Hello and welcome to my interactive tutorial.")
name = input("Your Name: ")
age = int(input("Your age: "))
city = input("Where do you live? ")
email = input("Please enter your email address: ")
Output:
Hello, and welcome to my interactive tutorial.
Your Name: Sam
Your age: 28
Where do you live? London
Please enter your email address: sam@abcxyz.com
Thank you very much, Sam, you will be contacted at sam@abcxyz.com.
Before I begin explaining what a statement is, let me pose you a simple
question. When was the last time you had to choose between two things,
depending on the elements like what you prefer, what you can afford, what
is near, and what isn’t? Whenever we make decisions, we take into account
quite a few components and elements which will eventually influence our
decision accordingly. Similarly, to help us with such issues, we use
statements, and that is exactly what we will be looking into.
In the simplest definition, Statements nothing more than instructions that
Python interpreter understands and executes. We have been writing some
ourselves when we set values to variables.
Statements, where we assign values to variables, are called assignment
statements. However, as long as Python is being discussed, generally,
statements refer to ‘if’ statements.
The ‘if’ statement is what provides Python with a situation and allows
Python to take appropriate action ‘if’ a given situation is true. Otherwise, it
takes another route. Sounds easy, and it is actually interesting too. Let us
see how we can create our very first ‘if’ statement.
Here’s the situation. A user wishes to sign in using their account. The
prompt asks for the passcode only. If the user inputs the right, case-
sensitive, passcode, he should be allowed access. If the user enters the
wrong password, it should not go through and inform the user that the
entered password was incorrect.
To do that, we first need to establish a password. You can either come up
with your own pre-defined one or ask the user to create a new passcode and
then re-enter it. I leave the choice up to you.
password = input("Create a password: ")
print("Welcome to the portal")
So far, I have only asked the user to enter a password of their choice. If you
wish, you can set any string or numbers as a password. Next, I created a
little welcome greeting. Now, we shall ask the user to enter their password:
password_check = input("Please enter your password: ")
The only thing worth noting here is that I changed the name of the variable.
If you are wondering why that is because had I used the same variable
name; it would have updated the password, instead of comparing it. Since
we wish to verify the password, we will need to use a different variable.
Now, the customer has given us two pieces of information. Here, we tell
Python what to do if the password matches.
if password_check == password:
print("Successful! Welcome back!")
There are two things to notice here. Whenever you type in ‘if’ as your first
word, PyCharm will detect that you wish to create an ‘if’ statement. The
color of ‘if’ will change to denote the same. After ‘if,’ we need to define
our condition. To do that, you may have observed that I used “==” instead
of a single equals sign. These signs are called Operators, which we will
discuss later. All you need to know here is this:
‘=’ is used to assign a value
‘==’ is used to either equate two variables or compare to see if the two are
exactly the same.
In the above instance, we will use this comparison operator. Here is the
most interesting bit; unlike all the codes we wrote so far, this line ends with
a colon ‘:’.
Every conditional statement, such as the ‘if’ statement, ends with a colon in
Python to create a block of code that will execute under that colon. The next
line will begin with an indentation. Do not remove that indent as that would
cause confusion. Since I had already set the condition, which quite literally
reads as “If password_check is exactly the same as password” and now I
added the command that it needs to carry out if the condition is met. When
you execute this program, you will begin with the prompt asking you to
choose a password. That would be stored as a variable named password.
Next, the prompt will ask us to type in the password once again for
verification or for login purposes. Whatever we type here will be stored in a
variable called password_check. Now, Python will compare the two values
and see if the two are exactly alike. If so, it will print out a success message.
I am quite sure that you have just tried to enter the wrong password
deliberately. It ended the program altogether without any warning, right?
There is a reason for that. We have only defined the ‘if’ condition. We
never got to the part to define the ‘else’ condition.
The ‘else’ condition is the final condition, and it usually comes into play
when the ‘if’ condition or others are not true and are not fulfilled. To do
that, we will add two lines of code beneath the first one. Now, the entire
program should look like this:
password = input("Create a password: ")
print("Welcome to the portal")
Notice how ‘else’ statement needs no indentation here, and it does not
require you to provide additional conditions either.
Now, I will run the code twice. Once correct and the other incorrect. Let us
see how it works:
Correct password
Create a password: 123
Welcome to the portal
Please enter your password: 123
Successful! Welcome back!
Incorrect password
Create a password: 123
Welcome to the portal
Please enter your password: 122
Sorry buddy! That's a Nay!
else:
print("You know what, forget it!")
elif number == 2:
print("You hate being alone, right?")
elif number == 3:
print("The more, the merrier, is it?")
else:
print("Really? You can't follow simple instructions, can you?")
We created another variable within the first condition. If the user decides to
settle for one, the prompt will ask the user to enter another number. We used
the conversion here to convert the incoming number to afloat, as it will
have a decimal figure.
We then created another condition which defines the upper limit and the
lower limit. To add a little fun to it, there is no correct number to choose
from here. Regardless of what the user may choose, they will either receive
a message to state that they went a little too high, or one that will encourage
them to go higher. The rest will always leave the user in a bit of a puzzled
state.
This kind of conditional statement within a conditional statement is called a
nested statement. This entire block of code can be avoided if the user
decides to go for any other number than the triggering point.
These can sometimes be highly useful. You may have already been using
these on Facebook, Netflix, and other major platforms. These are designed
to refine the results further.
While we did all this, there was something I was hoping you would ask.
“Why do we have to put in a value and restart the program every time to
test out another value?”
It does make sense. It will be highly annoying if your program restarts from
the beginning every time it reaches some result, whether positive or not. It
would be just like the old days where games on Nintendo would be fun,
right until you run out of lives, and the screen says “Game over” and restart
from the beginning. Frustrating days, weren’t they?
To address such an issue, we use what are called ‘Loops’, and these are
equally as important as the conditional statements, as we saw above.
else:
print("You ran out of chances")
“Wait! Why did you use an ‘else’ with the ‘while’ loop? I didn’t know if
you can do that!”
Now you do! The ‘else’ is not just limited to ‘if’ statements; you can use it
with a while as well.
Here’s what the end result looks like:
The problem with this would have been that the digit ‘3’ was only
recognizable by us. For any other programmer, this would not make any
sense. Therefore, we replaced that with a variable so that it literally
improves readability. Now, it reads like this:
“While guess is less than or equal to three:”
This is how you should always aim your codes to be. They should be
readable and easy to understand by everyone.
“<=” is yet another operator. Here, the values are either less than or equal
to whatever the value of the variable is on the other side.
We started by asking the user to guess, and that’s what we need as an input.
However, since it will be a whole number, we also converted the same into
an integer. After the user guessed the number, whether right or wrong, we
immediately need the program to add a value of ‘1’ to the number of
guesses. This is where we used an increment. But, unlike what we did
earlier, I changed a little and used the ‘+=’ operator. It basically means to
increase the value by whatever the digit you choose to write on the other
side. If you are more comfortable using the previous method, it will work
flawlessly as well.
Now, here’s the twist. We used an ‘if’ statement to let the program know
that if the user guesses the exact number, it should print out a message that
is appropriate for the occasion. Otherwise, the ‘else’ condition will take
place, as long as this is not the third and final guess.
Should the final guess wrong, the count will increase for the number of
guesses, and the while statement will no longer be true, in which case, the
‘else’ part of it will come into play and end the game.
The thing to notice here is the word ‘break’ that I used within the code. Go
ahead and see what happens when you remove this. If you guess your
numbers wrong, the code will work fine. And, if you end up inputting the
right value, instead of ending the game, it will still go on until the third
attempt is made.
To avoid that from happening, we use the ‘break’ statement to let the
program know what to do if the condition above the break statement is met.
Now, there is almost nothing left about the ‘while’ loop, let us move to the
‘for’ loops. Slightly different from what you might expect, but interesting
nonetheless.
To create a ‘for’ loop, we begin by using the keyword here. The word
‘char’ is just a variable we created. Notice how we did not define this
variable before. Whenever we use ‘for’ loops, we create what are called as
loop variables. These exist only within the loop itself, to carry out the loop
and its operations. Here, I used ‘char’ to represent ‘characters’ since Python
does not identify letters as letters.
What this means is “for every character in the word ‘Loops’”, print out the
characters. Surely enough, if you execute this code, you will end up with
this:
L
o
o
p
s
The system iterates over each of the components and then uses those
according to what the program says. Here, we only asked it to print
characters. It started with ‘L’ and then moved on to ‘o’ and continued until
there were no characters left.
It isn’t necessary that you use a string, you can use what is termed as lists.
These are a collection of values, either strings or numbers, stored within a
list. The lists are represented by a square bracket ‘[]’ and can hold as many
items as you like.
Let’s try that and see what happens:
for char in ["I", "Love", "Programming"]:
print(char)
Output:
I
Love
Programming
See how that differed? That is because when we used a single string, every
character was a different object. Here, the list holds multiple objects,
instead of printing them separately, it printed out whatever the value was
within each component of the list.
Here’s one more example, and this one has a new function for us to dive
into. Suppose you wish to print out the numbers from one to 20. Instead of
typing the entire numbers, we use a built-in function called range():
for the number in range(20):
print(number)
Here, we pass the higher end of the range as a parameter. Now, Python will
execute this for us, and the results will be exactly how you might imagine:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
See how it printed the numbers to 19 and not 20? That is because, for
Python, the first position is always considered as zero. If you scroll up, you
will see that the count started from zero. For now, do not get bogged down
there. We will discuss that when we discuss index numbers.
If you wish to set a specific starting point, you can do so by adding value,
followed by a comma, just before the 20:
for the number in range(10, 20):
Now the count will begin from 10 and end at 19. Let’s take that up a notch.
Suppose I want to print out numbers from 10 to 20, and I want 20 to be
printed, but I do not want all the numbers. I want the program to print out
every second number, like 12, 14, 16, and so on. You can actually do that as
this range function comes with what is termed as a ‘step’ for this function.
for number in range(10, 21, 2):
print(number)
Output:
10
12
14
16
18
20
Now, the program executes, starts with the first number, and knows that it
needs to jump two steps and print that number. This will carry on until the
final number, or the last possible number of iteration is printed. Notice, in
order to print 20, I had to change the value to 21 within the range.
E-commerce and e-shops use these quite a lot to iterate over the cart items
and deliver you the total price of your potential purchase. In case you wish
to see how that happens, here’s one more example for a ‘for’ loop.
Scenario: I have five items in my imaginary cart. They are $5, $10, $15,
$20, and $25 in prices, respectively. I want the program to let me know
what my total is. While I can use the calculator myself, or pause for a few
seconds and calculate the price myself, I want a quicker solution. You, as a
programmer, will need to create something like this:
prices = [5, 10, 15, 20, 25]
total = 0
for the item in prices:
total += item
print(f"Your total price is: ${total}")
Output:
Your total price is: $75
Let’s be honest. This was much more fun to do than using a simple
calculator, wasn’t it? Programming can be tough at times, frustrating too.
Sometimes, you might arrive at a point where you would spend the rest of
your day wondering what could possibly be causing you to have such a
nightmarish time with a program that seemed too simple to execute.
Relax! Every one of us faces that. It comes with the kind of work we do.
Programming can be quite deceptive and will take quite a lot of time for
you to master. What’s important is that you never give up. Should you feel
frustrated, grab a drink, have some fresh air, and calm your mind. The
solution would be more obvious than you might think.
Now that we have calmed down a little. Let’s get back to learning Python. It
is time to put an end to the loops by learning one more type of loop called
‘nested’ loop. If you recall, we have already seen a nested conditional
statement; an ‘if’ statement within an ‘if’ statement. Similarly, we use a
‘for’ loop within a ‘for’ loop to get things that we wish to acquire.
Wow! Look at that! A ‘for’ loop within a ‘for’ loop within another ‘for’
loop. That are a lot of loops right there. But, that is exactly how this will
work. What happens now is that the program initiates with the first position
of our loop variable ‘c’ while the remaining variables hold a value of zero.
Then, the loop starts again; this time, only ‘c’ jumps to a value of one while
others remain the same. This will continue right until ‘c’ reaches the end of
the range, after which ‘b’ will gain value of one. Hopefully, you see how
this is going. The result is as under:
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 1, 0)
(0, 1, 1)
(0, 1, 2)
(0, 2, 0)
(0, 2, 1)
(0, 2, 2)
(1, 0, 0)
(1, 0, 1)
(1, 0, 2)
(1, 1, 0)
(1, 1, 1)
(1, 1, 2)
(1, 2, 0)
(1, 2, 1)
(1, 2, 2)
(2, 0, 0)
(2, 0, 1)
(2, 0, 2)
(2, 1, 0)
(2, 1, 1)
(2, 1, 2)
(2, 2, 0)
(2, 2, 1)
(2, 2, 2)
Phew! That would have taken us quite some time to write. However, some
clever trickery of nested loops and just a few keystrokes later, we have it
right now we want it. That is how effective nested loops are. When you are
to deal with big chunks of data, you will want to rely quite a bit on nested
loops. These get the job done and are mighty effective too.
Now, since that is out of the way, let us focus on operators. Those pesky
little signs that keep on changing every now and then remember? We will
be looking into these to see how they work for us.
Chapter 5
The Types
Straight away, we begin by seeing some basic ones. When we talk about
arithmetic, the first few things to pop-up are the addition, subtraction,
multiplication, and division signs. Python is no stranger to these, either.
There are a lot of applications and programs designed using these. We will
be looking into those, too, I promise.
+, -, /, *
The above signs, not including the comma marks, are universal in nature.
Whether you speak English, Japanese, or Mandarin, you know you are
dealing with some basic operators. These operators are in use throughout
the world, at least within a calculator. Using these within Python at this
point in time, hopefully, should not be a problem for you. However, these
are not the only operators we use.
The ‘=’ sign, if you may recall, is not an ‘equal to’ sign in Python. It is an
operator that assigns a value to a variable. To equate something, we use the
‘==’ sign.
I am sure; you had already figured that out. What about these then?
!=
>=
<=
%
//
**
+=
Output:
True
The output value here will not be a number, but a Boolean value of ‘True.’
Here’s a more complex-natured one. Suppose you have a list of questions
for the user to check for loan approval. One of these questions will have
“Do you have any criminal convictions or recorded history?” to which the
banks will automatically refuse. In a programming language, we will create
an ‘if’ statement and use the same details as under:
age = 28
is_working = True
is_married = False
has_criminal_record = False
if has_criminal_record != True:
print("You are eligible for a loan!")
else:
print("Sorry, but you are ineligible for a loan")
Assuming that we fill these out, the application will automatically print out
that the person is eligible for a loan. However, change has_criminal_record
to True and then run the program. Now the program will execute the ‘else’
statement as has_criminal_record now matches ‘True’ and, therefore,
renders the ‘if’ condition void.
>= and <=
The “greater and equal to” and the “lesser and equal to” operators were
already used by us at least once. These are used in a similar fashion to the
‘!=’ operator. However, owing to the nature of these operators, we use these
for numbers, either integers or floats. These are also called as comparison
operators, and so is ‘!=’ and ‘==’ operators.
Let us put these to some use and see how they function. Mind you; this one
will take a little closer look. I have designed it deliberately to intimidate
you. If you read closely, you will immediately realize how easy it is to
understand what’s going on here.
print("Welcome to our online eligibility checker!")
age = int(input("Enter your age: "))
has_license = input("Do you have a license? [Y/N]: ")
if has_license.lower() == "y":
has_license = True
else:
has_license = False
salary = int(input("Your monthly Salary: $"))
if age <= 35:
print("The age is right!")
if has_license == True:
print("You have a valid license.")
if salary >= 3500:
print("Perfect! You are eligible.")
else:
print("I am sorry, but you are below our minimum requirement")
else:
print("Sorry, but you need to have a valid license")
else:
print("You are above our maximum age limit.")
Output:
9
This operator first divides the two numbers and then brings forth the
remainder as there is no further division possible. You can try and change
the value of alpha to 200, and the remainder will be two.
The ‘/’ is a straightforward division operator. Replace the modulus sign
above (alpha at 20) with the division sign, and you get the following result:
1.8181818181818181
Now, the point to note here is that we entered two integers, and the return
value was afloat. What if we just wish to settle for an integer instead?
That’s where we use the ‘//’ sign. Now, use this sign instead of the division
sign. The result should be ‘1’ only. The result will not be rounded off to the
nearest tenth. This is the floor division operator, which always returns an
integer value.
If, however, you wish to round off the value, you will need to use a function
called round(), and this is how you will do so:
alpha = 20
beta = 11
print(round(alpha / beta))
Output:
2
Finally, we have the ‘**’ signs. These are exponential operators. Now,
replace the division operator with the exponential operator, remove the
round function, and you will get the following result:
204800000000000
400? 20? No! The answer would be 25. Why? Because there is specific
precedence that operators follow. There are some who take higher priority
and are calculated first. Here is a simple way to explain things:
Exponentiate > Divide > Multiply > Add/Subtract
That is always the case in Python. And with that, we can say goodbye to
some basic operators and go to a little more advanced once.
The first logical operator we have here is the ‘and’ operator. What that does
is it creates a condition where both the former and the latter must be met. If
not, the entire block of code will not be considered, and the ‘else’ statement
will be executed instead.
Note: See how I did not assign any comparison operator for the
has_good_credit? That’s because the value for that is a bool value, which is
currently set to true!
If you read this code in plain English, it literally reads:
“If the salary is equal to or higher than the minimum salary, and has good
credit.”
Now, let us type in the values to see if this works:
Eligibility Checker 101
Please enter your name: Smith
Please enter your age: 34
What is your monthly salary? 5000
Congratulations Smith, You are eligible for a mortgage.
Now, let’s try to change the bool value to ‘False’ and see what happens:
Eligibility Checker 101
Please enter your name: Snow
Please enter your age: 30
What is your monthly salary? 6000
Snow, it appears you may not be eligible at this time
This happened because the first condition is met, but the second condition
was not satisfied.
So, you submitted the program, and a few days later, the client returns and
says, “Well, I would like you to change the program a little. This time, we
want our applicants to either have a good salary or good credit. Anyone
would do!”
Now, let us look at the code again. How can we do that without changing
much? That is where the second logical operator comes in.
The ‘or’ operator is used in such situations where one or the other condition
is true, in which case the program will execute the ‘if’ statement block. Let
us try it out by changing the ‘and’ to ‘or’ and keeping the has_good_credit
value to false.
print("Eligibility Checker 101")
name = input("Please enter your name: ")
age = int(input("Please enter your age: "))
salary = int(input("What is your monthly salary? "))
min_salary = 5000
has_good_credit = False
if salary >= min_salary or has_good_credit:
print(f"Congratulations {name}, You are eligible for a mortgage.")
else:
print(f"{name}, it appears you may not be eligible at this time")
Output:
Now, the code successfully executed and gave Nathan the good news. This
is because the ‘or’ operator informed Python, “Hey! Even if one of these
conditions is applicable, go ahead!”
Lo and behold! The world of logical operators. They make our lives so
much easier, don’t they?
Lastly, we also have one more logical operator called ‘not’ operator. This is
slightly tricky to understand, but bear with me on this one.
Suppose the same client returns and asks, “Hey! Good job, but I need
another chance. This time, I want you to code your program so that it only
works if the applicant has a good salary and not good credit.”
Sure, and to do just that, this is what we will do:
What the ‘not’ operator does is it changes the value of the second variable
from True to False, or from False to True. In this case, since the applicant
has no credit history, the condition fits. The interpreter will see this as
“Applicant has a salary that is greater than the minimum and does not have
a good credit history, which is true, then let’s go with it!”
The result will be as follows:
Eligibility Checker 101
Please enter your name: Nicole
Please enter your age: 29
What is your monthly salary? 8000
Congratulations, Nicole, You are eligible for a mortgage.
If you were to change the bool value to true, Nicole here would be left a
little sad.
And that about wraps up our trip to the world of operators. We saw the
types, and we saw their usages as well. These do take a little while to be
understood fully, but rest assured, they are super helpful. Continue
practicing these codes and use your own imagination to come up with
situations and scenarios where you may be able to use these effectively.
Chapter 6
Lists
They are exactly as they sound and function pretty much the same. A list, in
Python, is represented by square brackets ‘[]’ and it can hold multiple items
within it. You can store as many items or values as you like within a list and
recall each component easily.
Let us look at a simple list first to see how exactly it works. For that, we
have six imaginary volunteers; Joey, Chandler, Ross, Phoebe, Rachel, and
Monica. Let’s also assume that we have no idea of the obvious connection
to these names. Time to create our first list:
friends = ["Joey", "Chandler", "Ross", "Phoebe", "Rachel", "Monica"]
And we have our list created. Since we are using string values, we will need
to use quotation marks to let Python know that these are string values.
Suppose you do not know what’s on the list. You do not even know how
long the list is. Our target is to find out:
● The number of components within this list
● Value of individual components
To do that, we will first need to see how long the list is, and we can do just
that by using the len() function. The len() function basically displays the
length of characters, components or items within a variable or a list.
friends = ["Joey", "Chandler", "Ross", "Phoebe", "Rachel", "Monica"]
print(len(friends))
Output:
6
Now, we have obtained one piece of information. Moving to the next one,
let us find out what is at the start of this list. To do that, we will call up the
first element, and this is where the concept of index position comes in.
An index is the position of a component. Here, the first component is ‘Joey’
and to find out that, we will do this:
friends = ["Joey", "Chandler", "Ross", "Phoebe", "Rachel", "Monica"]
print(friends[0])
Here, we will use the square brackets and use the value of zero. Why zero
and not one? In Python, and in quite a few languages as well, the first
position is always a zero. Here, “friends[0]” essentially tells the program to
print the component with the first index position. The output, obviously, is:
Joey
Output:
Joey
Chandler
Ross
Phoebe
Rachel
Monica
There is another way to do this. Suppose you do not know the length of the
list, and you wish to print out the last recorded entry of the same, you can
do that by using the following method:
friends = ["Joey", "Chandler", "Ross", "Phoebe", "Rachel", "Monica"]
print(friends[-1])
Output:
Monica
The ‘-1’ will always fetch you the last entry. If you use ‘-2’ instead, it will
print out the second to last entry as shown here:
friends = ["Joey", "Chandler", "Ross", "Phoebe", "Rachel", "Monica"]
print(friends[-2])
Output:
Rachel
There are other variations involved here, as well. You can call the items
from a specific starting point. Using the same list above, let’s assume we
wish the prompt to print out the last three entries only. We can do that easily
by using the starting index number of the value we wish to print. In this
case, it would be the index number ‘3’:
friends = ["Joey", "Chandler", "Ross", "Phoebe", "Rachel", "Monica"]
print(friends[3:])
Output:
['Phoebe', 'Rachel', 'Monica']
You can also limit what you wish to see on the screen further by setting a
range of index numbers. The first number, the one before the colon,
represents the starting point. The number that you input after the colon is
the endpoint. In our list of friends, we have a range from zero to five, let us
narrow our results down a little:
friends = ["Joey", "Chandler", "Ross", "Phoebe", "Rachel", "Monica"]
print(friends[2:5])
Output:
['Ross', 'Phoebe', 'Rachel']
Remember, the last index number will not be printed; otherwise, the result
would have also shown the last entry.
You can modify the values of a list quite easily. Suppose you wish to
change the entry at index number five of the above list, and you wish to
change the entry from ‘Monica’ to ‘Geller,’ this is how you would do so:
friends = ["Joey", "Chandler", "Ross", "Phoebe", "Rachel", "Monica"]
friends[5] = "Geller"
print(friends)
Output:
['Joey', 'Chandler', 'Ross', 'Phoebe', 'Rachel', 'Geller']
It is that easy! You can use lists with loops and conditional statements to
iterate over random elements and use the ones which are most suitable to
the situation. Practice a little, and you should soon get the hang of them.
What about if you wish to add numbers or values to the existing lists? Do
we have to scroll all the way up and continue adding numbers manually?
No! There are things called methods, which you can access at any given
time to carry out various operations.
Here’s a screengrab to show just how many options you have available to
you once you press the ‘.’ Key:
We will not be talking about all of these, but we will briefly look at some
basic methods that every programmer should know.
Straight away, the ‘append’ method is what we use to add values. Simply
type in the name of the list you wish to recall, followed by “.append” to let
the program know you wish to add value. Type in the value, and that is it!
The problem with using the append method is that it adds the item
randomly. What if you wish to add value to a specific index number? To do
that, you will need to use the insert method.
Using an insert method, you will need to do this:
numbers = [99, 123, 2313, 1, 1231411, 343, 435345]
numbers.insert(2, 999)
print(numbers)
Output:
[99, 123, 999, 2313, 1, 1231411, 343, 435345]
The number was added right where I wanted. Remember to use an index
position that is valid. If you are unsure, use the len() function to recall how
many components are within a list. That should then allow you to know the
index positions available.
You can also remove items from a list as well. Simply use the remove()
method and input the number/value you wish to remove. Please note that if
your list has more than one value that is exactly the same, this command
will only remove the first instance only.
Let us assume you are presented with a list of mixed entries. There is no
order that they follow. The numbers are just everywhere, disregarding the
order. If you wish, you can sort the entire list to look more appealing by
using the sort() method.
numbers = [99, 123, 2313, 1, 1231411, 99, 435345]
numbers.sort()
print(numbers)
Output:
[1, 99, 99, 123, 2313, 435345, 1231411]
You know, you can also have it the other way around by using the reverse()
method. Try it!
To completely empty a list, you can use the clear() method. This specific
method will not require you to pass any argument as a parameter. There are
other methods such as pop() (which takes away the last item on the list
only) that you should experiment with. Do not worry; it will not crash your
system down or expose it to threats. The IDE is like a safe zone for
programmers to test out various methods, programs, and scripts. Feel free
and feel at ease when charting new waters.
Tuples
As funny as the name may be, tuples are pretty much like lists. The only
major difference is that these are used when you do not wish for certain
specialized values to change throughout the program. Once you create a
tuple, it cannot be modified or changed later on.
Tuples are represented by parenthesis (). If you try and access the methods,
you will no longer have access to the methods that you did when you were
using lists. These are secure and used only in situations where you are
certain you do not wish to change, modify, add, or remove items. Normally,
we will be using lists, but it is great to know we have a safe way to do
things as well.
Dictionaries
Unlike tuples and lists, dictionaries are different. To begin with, they work
with “key-value pairs,” which sounds confusing, I know. However, let us
look at what exactly a dictionary is and how we can call, create, and modify
the same.
To help us with the explanation, we have our imaginary friend here named
James, who has graciously accepted to volunteer for the exercise. We then
took some information from him such as his name, email, age, the car he
drives, and we ended up with this information:
Name – James
Age – 58
Email – james@domain.com
Car – Tesla T1
What we have here are called key pairs. To represent the same within a
dictionary, all we need is to create one. How do we do that? Let’s have a
look.
friend = {
"name": "James",
"age": 30,
"email": "james@domain.com",
"car": "Tesla T1"
}
We define a dictionary using {} braces. Add each pair as shown above with
a colon in the middle. Use a comma to separate items from one another.
Now, you have a dictionary called ‘friend’ and you can access the
information easily.
Now, to call up the email, we will use square brackets as shown here:
friend = {
"name": "James",
"age": 30,
"email": "james@domain.com",
"car": "Tesla T1"
}
print(friend["email"])
Output:
james@domain.com
Similarly, try recalling the other elements to try it out yourself. Once again,
I remind you that Python is case sensitive. If you recall ‘age’ as ‘Age’, it
will not work at all.
Suppose you wish to recall an item without knowing the key pairs within a
dictionary. If you type in a key named ‘dob’, the program is going to return
an error like this:
Traceback (most recent call last):
File "C:/Users/Programmer/PycharmProjects/PFB/Lists2.py", line 7, in
<module>
print(friend["dob"])
KeyError: 'dob'
There is a way you can check for values without the program screaming
back at you with red/pink fonts. Use the .get() method instead, and the
program will simply say ‘None,’ which represents the absence of value.
You can also give any keypair, that may not have existed before, a default
value as well.
friend = {
"name": "James",
"age": 30,
"email": "james@domain.com",
"car": "Tesla T1"
}
print(friend.get("dob", "1, 1, 1900"))
Output:
1, 1, 1900
Unlike tuples, you can add, modify, or change values within a dictionary. I
have already shown you how to do that with lists, but just for demonstration
purposes, here’s one way you can do that.
friend["age"] = 60
print(friend["age"])
Output:
60
Now, that wasn’t so bad, was it? This then ends our trip to the world of lists,
tuples, and dictionaries. You must pay close attention to these as you will
need to use a few of them, if not all, at once, more often than you might
imagine. The more you practice and familiarize yourself with lists, tuples,
and dictionaries, the easier it will be to create some incredible programs and
code inefficient codes at the same time.
Chapter 7
Functions
We began with almost no prior knowledge about Python except for a clue
that it was some kind of programming language that is in great demand
these days. Now, look at you, creating simple programs, executing codes,
and fixing small-scale problems on your own. Not bad at all! However,
learning always comes to a point where things can get rather trickier.
In quite a similar fashion, Functions are docile looking things; you call
them when you need to get something done. But did you know that these
functions have so much going on at the back? Imagine every function as a
mini-program. It is also written by programmers like us to carry out specific
things without having us write lines and lines of codes. You only do it once,
save it as a function and then just call the function where it is applicable or
needed.
The time has come for us to dive into a complex world of functions where
we don’t just learn how to use them effectively, but we also look into what
goes on behind these functions, and how we can come up with our very
own personalized function. This will be slightly challenging, but I promise
there are more references that you will enjoy to keep the momentum going.
Functions are like containers that store lines and lines of codes within
themselves, just like a variable that contains one specific value. There are
two types of functions we get to deal with within Python. The first ones are
built-in or predefined; the others are custom-made or user-created functions.
Either way, each function has a specific task that it can carry out. The code
that is written before creating any function is what gives that function
identity and a task. Now, the function knows what it needs to do whenever
it is called in.
When we began our journey, we wrote, “I made it!” on the console as our
first program? We used our first function there as well: the print() function.
Functions are generally identified by parentheses that follow the name of
the function. Within these parentheses, we pass arguments called
parameters. Some functions accept a certain kind of parenthesis, while
others accept different ones.
Let us look a little deeper and see how functions greatly help us reduce our
work and better organize our codes. Imagine, we have a program that runs
during live streaming of an event. The purpose of the program is to provide
our users with a customized greeting. Imagine just how many times you
would need to write the same code again and again if there were quite a few
users who decide to join your stream. With functions, you can cut down on
your own work easily.
For us to create a function, we first need to ‘define’ the same. That is where
a keyword called ‘def’ comes along. When you start typing ‘def’, Python
immediately knows you are about to define a function. You will see the
color of the three letters change to orange (if using PyCharm as your IDE).
That is another sign of confirmation that Python knows what you are about
to do.
def say_hi():
Here, say_hi is the name I have decided to go with; you can choose any that
you prefer. Remember, keep your name descriptive so that it is
understandable and easy to read for anyone. After you have named your
function, follow it up with parentheses. Lastly, add the friendly old colon to
let Python know we are about to add a block of code. Press enter to start a
new indented line.
Now, we shall print out two statements for every user who will join the
stream.
print("Hello there!")
print('Welcome to My Live Stream!')
After this, give two lines of space to take away those wiggly lines that
appear the minute you start typing something else. Now, to have this printed
out easily, just call the function by typing its name and run the program. In
our case, it would be:
say_hi()
Output:
Hello there!
Welcome to My Live Stream!
See how easily this can work for us in the future? We do not have to repeat
this over and over again. Let’s make this function a little more interesting
by giving it a parameter. Right at the top line, where it says “def say_hi()”?
Let us add a parameter here. Type in the word ‘name’ as a parameter within
the parenthesis. Now, the word should be greyed out to confirm that Python
has understood the same as a parameter.
Now, you can use this to your advantage and further personalize the
greetings to something like this:
def say_hi(name):
print(f"Hello there, {user}!")
print('Welcome to My Live Stream!')
The output would now ask the user regarding their name. This will then be
stored into a variable called user. Since this is a string value, say_hi()
should be able to accept this easily. Bypassing ‘user’ as an argument, we get
this as an output:
Please enter your name to begin: Johnny
Hello there, Johnny!
Welcome to My Live Stream!
Now that’s more like it! Personalized to perfection. We can add as many
lines as we want, the function will continue to update itself and provide
greetings to various users with different names.
There may be times where you may need more than just the user’s first
name. You might want to inquire about the last name of the user as well. To
add to that, add this to the first line and follow the same accordingly:
def say_hi(first_name, last_name):
print(f"Hello there, {first_name} {last_name}!")
print('Welcome to My Live Stream!')
Now, the program will begin by asking the user for their first name,
followed by the last name. Once that is sorted, the program will provide a
personalized greeting with both the first and last names.
However, these are positional arguments, meaning that each value you input
is in order. If you were to change the positions of the names for John Doe,
Doe would become the first name, and John will become the last name. You
may wish to remain a little careful about that.
Hopefully, now you have a good idea of what functions are and how you
can access and create them. Now, we will jump towards a more complex
front of ‘return’ statements.
“Wait! There’s more?” Well, I could have explained this earlier, but back
then, when we were discussing statements, you may not have understood it
completely. Since we have covered all the bases, it is appropriate enough
for us to see exactly what these are and how these gel along with functions.
Return Statement
Return statements are useful when you wish to create functions whose sole
job is to return some values. These could be for users or programmers alike.
It is a lot easier if we do this instead of talk about theories, so let’s jump
back to our PyCharm and create another function.
Let us start by defining a function called ‘cube’ which will multiply the
number by itself three times. However, since we want Python to return a
value, we will use the following code:
def cube(number):
return number * number * number
By typing ‘return’ you are informing Python that you wish for it to return a
value to you that can later be stored in a variable or used elsewhere. It is
pretty much like the input() function where a user enters something, and it
gets returned to us.
def cube(number):
return number * number * number
Before you even begin to create a class, or function, or any other kind of
component, always visualize what you want to get out of it. It makes things
a lot easier for you as a programmer.
At this point, you may be blank and might be struggling to come up with a
class to create. Let me help you out with one. Let us create a class to which
we want specific functions and methods attached to. We want this class to
do things other data types were unable to do so.
I will not be creating anything that may fall outside the scope of this book,
so what I have here is easily understandable. However, there are a few
things that might take you by surprise, but those are deliberate so that you
have every chance of understanding what they are.
class Instructor:
def __init__(self, name):
self.name = name
def talk(self):
print("talk")
me = Instructor("Keanu Reeves")
print(me.name)
me.talk()
The first thing to notice here is the naming convention I have used to name
the class. Always use an uppercase for the first letter for every word that
you may type when naming a class. You do not need to use underscores to
separate words either. If you were to name this class as your first class, it
would look like this:
class MyFirstClass
Next, we have the familiar ‘def’ keyword. But what about the double
underscores and init? You may have already noticed these when calling
methods. These are called constructors. For now, all you need to know is
that we call upon these to initialize something.
Then, we have a parameter that says ‘self’, and I did not put it there. It is
something that will come up automatically. It is referencing itself. We have
only added another parameter called ‘name’ to allow us to use strings as
names to display. Next, we gave the object an attribute called ‘name’, as
seen above. Attributes are required to provide your functions a greater
detail.
The next function is rather simple. We just created a function called to talk
and asked Python to print out the same on the prompt.
Moving forward, or downwards by two spaces, we created a variable called
‘me’ with an assigned value of the class we just created. Notice how I have
used class as a function (with parentheses). You might be wondering that I
just said moments ago that classes do not need parentheses, and yet, I am
using them here. When you are defining classes, you do not need these;
however, when you are using them, you will need to rely on them to pass
additional information.
Now, with the print command ready, I used my newly created class to call
upon an attribute of ‘.name’, which I created within this class. This then
allows the prompt to print out the name, followed by the last function,
which was again another print statement as defined above.
Classes are generally created so that other objects can be created using
these classes. Imagine two characters, Tony and Steve. We want each of
these to be objects carrying different attributes like name, age, and suit
color. To do that, we will first need to create a class. Let us go ahead and do
so.
class Heroes:
def __init__(self, name, age, color):
self.name = name
self.age = age
self.color = color
def introduce_self(self):
print("My name is " + self.name)
print(f"I am about {self.age} years old")
print("My costume color is " + self.color)
hero1.introduce_self()
hero2.introduce_self()
Output:
My name is Steve
I am about 40 years old
My costume color is Blue
My name is Tony
I am about 38 years old
My costume color is Red
Exception Handling
What exactly are exceptions? Why haven’t we come across this so far?
Well, we have, or at least you may have quite a lot of time but never noticed
before. Create any program to make it crash deliberately.
Here’s one that I created:
name = "Bruce Wayne"
age = 45
print(name + age)
Output:
Traceback (most recent call last):
File "C:/Users/Programmer/PycharmProjects/PFB/exception.py", line 3, in
<module>
print(name + age)
TypeError: can only concatenate str (not "int") to str
Process finished with exit code 1
See the error? Not the one in the middle, I am referring to the very last line.
It says the program ended with an exit code followed by the number one.
That ‘one’ is informing us that something went wrong, and the program
ended in a crash or abruptly ended. If the code were zero, it would have
meant that our code went through and got executed beautifully!
We, as Python programmers, are bound to know when such errors are about
to come. It’s called anticipating, and it is something you should have
already done when you say the first three lines of my latest code.
The problem is, we programmers would know what this code means. For
any ordinary user, they would have no clue what this means and would end
up searching YouTube libraries, just to find a video that explains what the
error code 1 means. There is a way we can address this situation, and that is
called exception handling.
Before we begin, just remember the bold text that says ‘TypeError’ on our
error that occurred just a moment ago. We will need to recall that a little
later.
Exception handling is where we tell a program to try a block of code and
see if the same works fine. If not, anticipate the type of error you will get.
Except for showing a console that is lit up with gibberish, we then tell
Python to print out a user-friendly text that means something. Don’t worry
about the words ‘try’ and ‘except’ because that is exactly what I will be
showing you now.
try:
name = "Bruce Wayne:"
age = 45
print(name + age)
except TypeError:
print("Please use a formatted string or convert age to a string")
We have just asked Python first to try a situation out. If the code is executed
without returning any errors, it’s fine. If not, it will type in a friendly
message instead of letting the users know what to do to avoid this. This will
prevent the application from crashing and keep users informed of the errors
they may have made. Now, let’s try and run this through to see what we get.
Please use a formatted string or convert age to a string
Process finished with exit code 0
That was expected. Since the exception caused here is different from the
one we have created earlier on, it just went through and crashed. Time to
put our thinking caps on and come up with an exception to handle this
situation.
try:
age = 45
age1 = 0
average = age / age1
print(average)
except ZeroDivisionError:
print("For God's sake! Who divides a number with 0?")
except TypeError:
print("Please use a formatted string or convert age to a string")
What do you think now? Will this work, or will we still end up with an exit
code of 1?
For God's sake! Who divides a number with 0?
And that’s how you do this! Now, everyone knows what went wrong and
how they can correct the error they may have unintentionally caused.
It is something of a trait to have to be able to anticipate errors coming your
way beforehand. It comes with practice, but it is certainly a trait to have for
any programmer from any corner of the world.
The better you are at handling exceptions, the easier your users will find the
program/application to use. They would know what needs to be done, how
to sort matters out, and how to continue having a great experience while
using your written programs.
This is almost everything that you would need to know about exception
handling. Now, you will no longer be bound to the silly errors that keep on
coming. Well, at least your users will not have to face those anyway. Create
messages for such exceptions which hold a precise meaning and deliver
information to the end-users so that they do not have to rely on someone
else to figure out what just went wrong here. For programmers, you can
also add some notes within your code. These are not seen as a part of code
when they are being executed. These are called comments and are
represented with a # sign. To give you an example, here’s one:
try:
age = 45
age1 = 0 #change this age to something else
average = age / age1 #to find out the average age
print(average)
except ZeroDivisionError:
print("For God's sake! Who divides a number with 0?")
except TypeError:
print("Please use a formatted string or convert age to a string")
If you execute the program, it will still function normally. These are notes
which you will find in quite a few programs and may have seen some
already. It’s a good idea to use these if you wish to share your program and
code with other programmers or users.
With that said, it is time to wrap this up and move on to our final frontier. I
shall wait for you in Chapter 9.
Chapter 9:
class Bikes:
def speed(self):
print("Fast")
Sure enough, that does look simple, but imagine how many lines would you
have to re-write when in a real-life situation? This poses more issues than
you might think up of. Imagine you had to copy and paste the same line of
code for more than 20 classes you defined further into your program. In the
end, you find out you had some values wrong at the start. This means the
rest will now need to be changed individually as well. Why go through such
hard work? Instead, let’s see how inheritance can help us out here.
We begin by first creating a parent class. Since cars and bikes are modes for
transportation, we will create a class called ‘Transport’ to begin the process.
Once done, we simply move the entire block of code we were interested in,
right inside this new class. It should now look like this:
class Transport:
def speed(self):
print("Fast")
Easy, right? It gets a lot easier now. To inherit these qualities, all you need
to do is this:
class Transport:
def speed(self):
print("Fast")
class Cars(Transport):
class Bikes(Transport):
By passing the class name ‘Transport’ into parentheses of the new classes,
we are telling Python, “Hey! They will inherit qualities from their parent
class.” But here’s a problem. To show the problem, it’s best to look into this
screenshot.
See how at line ‘9’ the letter ‘c’ has a red line underneath? That’s Python’s
way of saying that it is not happy with us. To avoid that, all we need is to
pass a word called ‘pass’ within the sub-classes. This way, Python knows it
does not need to worry about anything within the classes.
class Transport:
def speed(self):
print("Fast")
class Cars(Transport):
pass
class Bikes(Transport):
pass
Now, you can easily create objects as we did earlier on with our two heroes
‘Steve’ and ‘Tony.’ You can also call upon their specific attributes as well.
So far, we have only set one attribute, which is speed.
class Transport:
def speed(self):
print("Fast")
class Cars(Transport):
pass
class Bikes(Transport):
pass
ferrari = Cars()
ferrari.speed()
yamaha = Bikes()
yamaha.speed()
The result will print out the word ‘fast’ for both. However, since bikes and
cars are two separate things, you can add exclusive attributes to each.
Maybe the number of wheels, the engine position, the passenger capacity,
and so on. But, to do that, you will need to remove the word ‘pass’ as we no
longer want Python to skip through the block of code within a specific
class. I designed some of the above. Sorry that this is long, but I have tried
my best to keep it as readable as possible.
class Transport:
def speed(self):
print("It is really fast")
def tyres(self, number):
print(f"It has {number} tyres.")
def engine(self, name):
print(f"It has a massive {name} engine.")
class Cars(Transport):
def make(self, name):
print(f"It's a {name}")
class Bikes(Transport):
def wheelie(self):
print("It can wheelie like crazy")
ferrari = Cars()
ferrari.make("Ferrari")
ferrari.engine("V12")
ferrari.tyres(4)
ferrari.speed()
yamaha = Bikes()
yamaha.engine("Twin-V")
yamaha.speed()
yamaha.tyres(2)
yamaha.wheelie()
The results are rather easy to understand. But, for the sake of knowledge
and information, here are the results:
It's a Ferrari
It has a massive V12 engine.
It has 4 tires.
It is really fast
It has a massive Twin-V engine.
It is really fast
It has 2 tires.
It can wheelie like crazy
This is how inheritance makes our lives so much easier. Instead of typing
all those codes, we were able to make this easy. This is the magic of
inheritance. Remember this, and you will no longer be writing hundreds of
lines of code over and over again.
With that said, let us now move on to our last two components: modules
and packages.
Do not be alarmed by these two words. They are far easier to understand
than they sound like. We shall first begin by having a look into what
modules are and then proceed towards packages.
The module is essentially a file in which there is some Python code that has
been written by either you or someone else. We normally use modules for
organizing our codes in an organized fashion. Think of a supermarket with
multiple aisles where each one is labeled clearly to let us know what we can
expect within these aisles.
Similarly, modules are files that have codes within them performing a
specific task. These can then be saved and later imported to other Python
programs for use. Yes, you read that right. Create a good function now and
use it for eternities to come.
So how does that work? Suppose you have a simple distance converter. This
converter converts kilometers to miles and vice versa. Let us first begin by
defining these two functions:
def kms_to_miles(distance):
return distance * 0.621
def miles_to_kms(distance):
return distance * 1.609
Now we have our functions; it is time to save them as a separate file. To do
that, go to the project browser window (the one on the left of the typing
area), right-click on the project name, and choose the new>file. Name the
file as distance_converter, or any other name that you fancy and add a .py
extension at the end. Once done, a new blank page will open. Simply cut
the entire code from the previous file into this one, and that’s it.
Now, our main file is empty. It is time to ‘import’ these converters within
our file. To do that, all you need to do is to type in the following:
import distance_converter
As soon as you press enter, this will be greyed out. That is perfectly fine.
Now, the converters are imported and, hence, usable for us within this
program. If you are not happy with the name, which may be a useful thing,
later on, you can always rename these by doing the following:
import distance_converter as a converter
This will then import the converter and then give it the name you just
assigned. To test, simply type the name you chose and press the ‘.’ Key to
access the functions available. You should now be able to see both the
kms_to_miles and miles_to_kms functions ready to use.
import distance_converter as converter
print(converter.kms_to_miles(160))
Output:
99.36
And there you have it. The module is working elegantly, and you were able
to convert the figures easily.
Sometimes, you might not wish to import the complete module with all the
functions. It is a possible scenario that you may just want to use a specific
function from the said module and wish to import only that. Makes sense,
right? Fortunately, that too can be done. For this, let us assume I only wish
to import the miles_to_kms function from the converter module. Here’s
how I can do that:
from distance_converter import miles_to_kms
Right now, we know there were only two functions, but what if there were
more than 10? To check, simply type the first few bites, and right after the
space following the word ‘import’ press ctrl+space to access the list of
functions available within the module. Choose the one you are interested in,
and Bob is your uncle!
from distance_converter import miles_to_kms
print(miles_to_kms(100))
Output:
160.9
Let us do things a little differently here. Let us create a little function first
whose job is to identify the largest number within a set of random numbers
(like we did before) and store it as a separate module. We will then call the
same and provide it with a list of numbers to identify the largest entry and
print out the same on the console.
def high_number(numbers):
max = numbers[0]
for the number in numbers:
if number > max:
max = number
return max #We need a return value
Save this in a separate module called max_number.py and then later import
the same.
from max_number import high_number
Output:
7564654
Let’s see what happened here. We initially defined a function where we first
began by declaring a variable with a numbers[0] value. We then initialized
the ‘for’ loop to iterate over individual components of the list. The
‘number’ is a loop variable, followed by the ‘if’ statement that defines what
condition needs to be met for ‘max’ to change value. In the end, we asked
Python to return us with a value. Simple, right?
We then imported this into our new file, provided it with a set of list
numbers. Here, we declared a variable called max (since this program has
never seen max before) and gave it a value that will be driven through the
function using the list of numbers. Eventually, we printed out the result,
which, in our case, was the largest number of the list.
This is how we use modules. Now, it is time for the last bit of the learning
process. This is where we meet packages and find out what they are.
Packages
Modules are files with codes in them, and similarly, packages are
directories, or folders, that contain multiple files within them. We use
packages to ensure that we organize our files accordingly. If you were to
create hundreds of files and a good chunk of them belonged to calculations,
you can create a package directory within PyCharm and Python with an
appropriate name and move all such files within this new folder.
To create a package file, right-click on the project name and choose the
Python package. Instantly, you will notice that it has one special file within
it by default. It is the __init__ file that initializes the package and allows
Python to know what this is.
Now, let us add a module to this newly created package. We shall call this
‘test1’ and give it a function within it. Remember, this file needs to be
created in the new package we created.
def test():
print("This is just a test")
We gave this as a function for the module. Now, let’s browse into one of our
old files within the previous folder. If you like, you can create an empty file
as well. Now, since we are in a different folder, and we need to import this,
things will be slightly different. If you try and use the previous method of
“import test1”, it will not work as the directories are different. Instead, we
will do this:
import test.test1
This lets Python know that you are importing a module called test1 from a
Python package called test. Now, you will be able to use the function easily.
There are far too many packages and modules available online, directly
from their sources, which you can use for quite a lot more than you might
imagine. You can browse around the internet and find ones that may be
more suited to your type of programming. However, the principles remain
the same.
Now, we have effectively learned everything that a beginner should know
about. You are all set to set sail and seek out your true calling and create
programs that are ready to take the world by storm. All it needs is practice
and patience.
Chapter 10
Remember
There are a few things you should always remember and be habitual of
when seeking out a career in programming.
You should stick to the clean-code practice and write code that is easy to
understand and read for any programmer. The cleaner you organize your
code, the better and more effective you will be as a programmer. Remember
to use modules and packages to organize your files and modules further
accordingly. You never know when you may need them again. It is always a
good idea to have the codes and functions you wrote stick around.
You can find various exercises online and even have some great tutorials
from places like Udemy and Coursera to fine-tune your knowledge further.
If you are stuck on a specific part and are unable to wrap your head around
it, take a break and think it through. Most likely, you will find a solution on
your own. If not, the internet awaits to answer all your distress calls.
Python is a well-documented language. There is every possibility that you
may find your answers within the documents provided on Python’s website.
Mr. Van Rossum certainly did think this one through. Make use of these
documents where possible and get further details about things that
otherwise might sound confusing to you.
As a programmer, think out of the box. Think about how you can change
things and make them more simple. Take everyday examples where you
think you can use your knowledge to create programs that can ease your
life. You never know, you might just come across a commonly faced
problem and fix it; one good thought is all that stands between you being
you and you being the next big name for the industry.
With that said, I bid you all farewell and the best of luck. May your future
be as bright as the sun!
References
Briggs, J, R. (2013): Python For Kids. San Francisco, CA. No Starch Press
Matthes, E. (2016): Python Crash Course. San Francisco, CA: No Starch
Press
Payne, B. (2015): Teach Your Kids To Code. No Starch Press
Python Workbook
Learn How to Quickly and Effectively
Program with Exercises, Projects, and
Solutions
PROGRAMMING LANGUAGES
ACADEMY
Introduction
This workbook has been created for practice and to allow readers of the
crash course to further enhance their knowledge, understanding, and usage
of Python as a programming language.
If you have already gone through “Python Programming For Beginners:
The Ultimate Beginner’s Guide to Learning the Basics of Python in a Great
Crash Course Full of Notions, Tips, and Tricks,” then this book is designed
to further assist you in practicing all that you have learned so far.
Keeping true to the nature of the previous book, we will be looking into
fun, intuitive, and challenging exercises. These will test your ability and
knowledge as a programmer and ensure that you are always prepared to
tackle situations, questions, and can identify errors. The exercises compiled
here are taken from various sources, the links to which will be provided at
the end of the book for your convenience. Should you like, you can visit
these links for further exercises and test your programming skills to the
max.
A great programmer is one who constantly practices his coding skills, can
solve technical issues, and can identify the kind of solution required to
resolve a situation. Our aim with this book is in-line with this concept,
which is why you can expect various types of exercises, projects, and tests
to learn from.
For your convenience, all solutions to questions and problems are provided
in the last chapter. Refer to these when you feel you are unable to figure the
problem out yourself. You may also refer to the first book from time to time
to refresh your concepts and further clarify any ambiguities you may have
during the process of learning and applying Python as a programming
language.
There is no harm in admitting defeat. I assure you, I have been there a
thousand times. If an exercise or question seems to be too much, remember
to take it a little bit at a time. The better your state of mind, the clearer
things will be for you.
Ask any successful programmer in the world, and they will confirm the
same: practice does make a programmer perfect. In the beginning, you
might have been struggling with using PyCharm to write your code.
Eventually, with a bit of practice, your pace started to increase. This is
because you’ve now adapted to the IDE and the overall environment and
feel of Python. The more you hone your skills, the more fluently you will
type out your programs.
These exercises are designed to ensure you always have something to
practice on. Once done with practicing the exercises as shown here, modify
them at will to further create complex programs on your own. It is a perfect
way to move into the intermediate and advanced levels of being a
programmer. Every programmer goes through thousands of such miniature
projects to gain perfect command of any language. While Python is
comparatively easier to understand, do not underestimate the language. It
can get tricky rather quickly, and with poor knowledge, you might end up
going in circles.
The previous book has indeed taught you quite a few things. I have ensured
that I created quizzes, exercises, and questions to test every bit of that
knowledge. This way, not only do you get to recall what you learned, but
you also get to see the code in action by applying the solutions you think
would be right. I do not claim to be the greatest programmer, nor that I am
anywhere near being one, but what I can guarantee is that these exercises
will certainly keep you on your toes and get you a step closer to becoming a
great programmer yourself.
The projects are designed for your independent exploration. You have the
entire internet to help you out with inspiration and ideas. Use the
knowledge you gathered in the previous book and the experience that you
will gain here to come up with more complex, more interactive programs
that you can write for the projects I have chosen for you. These are projects
which can make their way into the market as well, if you think out of the
box and apply slightly more advanced logic and knowledge. Nothing is
impossible, and programming is no different.
Sea of Questions!
These questions, while they may sound easy, are designed to revisit some
basic elements of python. Some of these may have options, while others
may not. Do not be intimidated by these questions. Try and answer as many
of these as possible.
Q-1: From the options given below, identify which of these is written in
Python?
Code-1:
using system;
var username = console.readline("Please enter your name: ");
console.write("Hello " + username);
Code-2:
<html>
<head>
<title>"Why write Python?"</title>
</head>
<body>
<p>
print("Hello World!")
</p>
</body>
</html>
Code-3:
import turtle
def my_function(name):
print(f"Hello {name}")
my_function("Sam")
Code-4:
var name = "Mr. Marvel";
console.log("My name is " + name);
I am sure you see some familiar things here. Take your time and analyze
each of these closely. The answer is right there, all it needs is a keen eye to
pick it out! It’s quite interesting to see that most of these seem to be using a
familiar setup. It does take time for one to be fully familiar with the syntax,
but once you are familiar, you should have no trouble figuring this out.
Visit any of the old exercises we did in the previous book. Try and match
the way the code was written to the ones presented here. You should have
your answer shortly!
Moving on to our next question, I promise it will be more questions and less
of me, but I need to ensure I provide some explanations were needed to help
those who may have picked up the book after a while, just to refresh their
concepts.
Let us now begin a series of questions to test your understanding.
Q-2: How can you check if you have Python 3.8.x installed on your
system?
A. Check if you have PyCharm installed on your system. If so, you
have the latest Python version installed.
B. Run the command python --version in PyCharm to check for the
version.
C. Run the command python in the command prompt for Windows to
check the version. Run python -v on Mac and python3 on Linux to
get the version.
D. Visit the Python website to see if it can identify your version of
Python.
Q-3: What is the language named after?
A. Monty Python’s flying circus
B. The reptile Python
C. To honor an endangered species of Python
D. Just a random name that caught on
Q-4: How does each line in Python end?
A. With a colon ‘:’
B. With a semicolon ‘;’
C. With a full stop/period ‘.’
D. None of the above
Q-5: What does the acronym IDE stand for?
A. International Day for Electronics
B. Integrated Developing Environment
C. Integrated Developer Environment
D. Integrated Developing Engineering
Q-6: How is a string represented in Python?
A. With a single quotation mark ‘’
B. With a double quotation mark “”
C. With either of the above.
D. None of the above.
Q-7: What is a variable?
A. It’s a function in Python.
B. It’s a method in Python.
C. It’s a user-created container holding immutable values.
D. It’s a user-created container holding values that can be modified.
Q-8: How would you print a string that says He said, “Yes!”?
A. print(“He said, “Yes!”)
B. print(f“He said, “Yes!”)
C. print(‘He said, “Yes!”’)
D. print(He said, Yes!)
Q-9: Running the code as shown, what will the output be?
num = '5' * '5'
print(num)
A. 25
B. 5, 5, 5, 5, 5
C. ‘5’ * ‘5’
D. TypeError: Can’t multiply sequence by non-int of type ‘str’
Q-10: If you run a code that ends up with an error, it will cause
PyCharm to crash.
A. True
B. False
C. Depends on the type of code written
D. None of the above
Q-11: Which is the correct method to set the value for a bool
‘is_married’?
A. “True”
B. True
C. ‘True’
D. true
Q-12: Which of the following is a formatted string?
Code-1:
name = "Jiovanni"
age = 41
print("Hi, I am name and I am age years old")
Code-2:
name = "Jiovanni"
age = 41
print(f"Hi, I am {name} and I am {age} years old")
Code-3:
name = "Jiovanni"
age = 41
print("Hi, I am " + name + " and I am " + age + " years old")
Code-4:
name = "Jiovanni"
age = 41
print("Hi, I am [name] and I am [age] years old")
Q-13: To name a variable called first name, which method is correct?
You can choose more than one answer to the following question.
A. firstname
B. FirstName
C. first.name
D. first_name
Q-14: Choose one or more answers which apply. Clean-code practice is:
A. To keep our workstations clean.
B. To name our variables and functions appropriately.
C. To improve readability.
D. To ensure the code is not breaking any laws.
Q-15: Which of the following is the correct way to create a variable
named ‘test’:
A. def test():
B. test.create
C. test = “”
D. print(test)
Storing/Recalling Information
While this section will mostly talk about the aspects of information itself,
we will also be ensuring that we maintain our practice of clean-code to help
programmers better understand the program itself. Expect a few issues
where the program might be right, but the naming could use some help. In
real-life situations, you will often encounter such issues and hence would
need to re-address the names to make the program more meaningful and
improve the overall readability of the code. With that said, let us begin!
Task-1: A YouTube streamer decided to conduct a survey where users
were asked to provide feedback on what they would like to watch in the
next stream. Your job is to create a program that uses the following
information and prints out the result of what the user chose, along with
a thank you message.
What shall I stream next?
a) Days Gone
b) Resident Evil 2
c) Fortnite
d) Apex Legends
e) Death Stranding
f) Surprise Us!
The ending message should be:
You have chosen (option). I appreciate your time and hope to see you in
the next one!
The exercise is fairly simple. Most of these will require you to print out
information and then store the user-input value. Design the program so that
it can understand what ‘a’ or ‘b’ or any character that the user chooses is,
and then print the same out in the end greetings. You do not have to worry
about printing out the name in the end. Just the letter of the selection will do
for now.
Remember, the case-sensitive nature of the program still haunts us. Make
use of methods like .lower() to ensure it matches our requirements. I will be
providing my version of the program in the last chapter as a solution. For
now, keep thinking, keep coding.
Hint: While you can use an ‘if’ statement, I would recommend bypassing
that for now. Try and think of more basic means to store and recall values.
This can easily be done without the use of logic and if/else statements. We
will revisit this exercise in the future to make it a little more complex and
appealing at the same time.
Task-2: A dentist wishes to have a program created for his website
where the customers will be presented with multiple services. The
customer will choose the option and will be presented with a total for
the service that is payable by the customer. The services are given, as
shown below:
a) Root Canal Therapy - $250
b) Oral Hygiene Check - $50
c) Emergency Injury Treatment - $100
d) Post-Procedure Check-up - $150
e) Routine Check-ups and Consultation - $75
For advanced payments, customers get a 50% discount.
Design a program that provides the customer with all the necessary
information and gives a total according to what the customer chooses.
Confused? Let me give you a hint. You cannot store two values within a
single variable unless you intend to create a list here. We are not aiming for
that. You can either create two separate variables, service_a and price_a, or
you can simply use conditional statements to enhance the program further. I
leave the decision up to you.
I would prefer to use the latter, though. It is a lot easier and less messy.
So far, we have seen two simple exercises. Now, you will have probably
realized that our programs can grow increasingly big and lengthy, the more
complex we try to make them. The more information you have with you,
the more lines of code will be used up. In typical situations, you will
encounter programs that span well over 400 lines on average, and these are
simple scripts used by programmers for various purposes.
I honestly do not mean to scare or intimidate you at all, but here’s a little
fact for you to digest.
The Mac OS X is believed to be the largest program ever written. It
contains well over… wait for it… 85 million lines of code!
If you were to print that out and lay the regular A-4 sized papers in a
straight line, you would cover a considerably large distance.
However, we are not here to set a world record, at least not yet. Our motive
is rather simpler and kinder to our fingers and mind.
These exercises will test or have already tested your knowledge of creating
variables, storing user-input information, modifying them (perhaps), and
recalling them for simple calculations as well. At the heart of every
program lies good and solid information. Without this, programs will have
no reason to function.
So now that we have catered to these two exercises, let us move on ahead
and see what else we can do.
Task-3: A college campus has decided to create a program that will
determine the eligibility of an applicant based on a few questions and
conditions. The college in question has asked you to create a program
to record the following pieces of information:
a) First name
b) Last name
c) Age
d) Overall score on their latest test result (out of 600)
e) If seeking scholarship
Based on the following conditions, the eligibility for admission and the
scholarship will be decided:
For Admission:
● The student should have achieved at least a 60% overall score or
above for admission.
For Scholarship:
● The student must have at least a test score of 80% to be eligible
for the scholarship.
Create a program with data from three different students who have
acquired a 471, 354, and 502 accordingly. Print out their results based
on the above conditions.
This exercise will be fairly long and will require you to use the information
and conditional statements to execute it to perfection. It might be wise to
point out that such projects are actually in place, and a loosely similar
module is being used for Canada’s Competitive Ranking System (CRS)
score calculation for immigration purposes as well.
When solving complex programs and situations, anticipate where you
should set variables and use them. If you miss out on key positions, your
program will have information, but it will not function or be utilized
properly.
It is essential to point out that you will need to have a basic understanding
of mathematical operations like multiplication, division, and so on, as these
greatly help you create better programs.
Python allows you to get as creative as you can. If you believe you are
bound by restrictions, you will be surprised to learn that there aren’t any.
You can apply Python to practically everything to come up with programs
that can tell you if you have the right ingredients for a recipe or the right
amount to pay off your debts. You can use it to make a predictive program
that can predict possible outcomes so that you may prepare for all of the
eventualities and so on.
Major business organizations use such programs, which may seem simple
but have quite a lot going on in the background. As a programmer, it is our
job to realize what needs to be done, how it will be executed, and how the
desired result can be achieved. Always use a blank paper to draw out the
flow chart. There is no specific flowchart for you to follow, which means
that you can come up with your ideas on your own and map them out. It
greatly helps with the programming part of the entire exercise. Go ahead
and try it for the exercise above (if you haven’t already done the exercise);
otherwise, use one for any of the exercises you will encounter later on.
Project - 1
Before I provide you with your first project, let me quickly shed some light
on what you can expect from these projects.
Every project will be unique, as each one of us will have different ideas
about how to carry out the task and execute the same. The projects will be
designed to provide you with seemingly simple tasks, only to find out that
you may have to do a little more than just copying and pasting blocks of
code from one file to another.
Use your coding knowledge from all sources, as these will not be bound to
individual chapters. Projects are where you will encounter all kinds of
problems, situations, and scenarios. To solve these, or finish them
successfully, you will need to use various methods right from the beginning,
all the way to the end of complex matters like functions, classes, and
modules.
I will be providing you with links from which you can download specific
modules, libraries, or classes to help further make the process easier. You
already know how to import them into your PyCharm using the “from x
import y” or “import xyz” method. Try and make a simple-looking scenario
complex and interesting. Continue developing these projects with advanced
knowledge that you will hopefully gain after this book. A program is never
truly complete. Even the best programs and software continue to be updated
with newer knowledge, modules, and variations.
Keep on practicing and adding more to these projects. Who knows, you
might end up with something far superior and more useful than just a
message that says “Hello World” at the end.
Task:
Create a simple game of “Rock, Paper, Scissors,” where the computer
randomly generates value and asks the user to input their selection. The
result should show whether the user wins or loses, or if it is a draw.
Requirements:
To complete this project, you will need to use the following:
Packages:
From random import randint – This will be your first line of code. Random
comes pre-installed and allows you to force the computer to randomize the
selection. This will help you in ensuring that every turn is unique and
unpredictable.
There are quite a few ways you can complete this project. As a reference, I
will share my solution for this project at the end of the book as well.
Please note that I wish to encourage you to explore the world of Python and
use your genuine approaches, communicate with the community, and learn
better ways to code. For this reason, I will not share the details on the
projects moving forward. I will gladly share the answers to questions and
solutions to other problems. The rest, I invite you to use your power of
deduction and programming to learn better.
So far, we have gone through some exercises, questioned what was right
and what was not. We even initiated our very first project, which is quite
challenging in all fairness. However, everything hinges on how well you
understand your basics. The better you know them, the easier it will be to
move from a beginner to an intermediate programmer and eventually to a
skilled programmer. If you are unsure about certain aspects, it is always a
good habit to revisit the concepts and revise what you have learned.
Time to say goodbye to variables and storing values and move on to our
friends, the statements, and loops.
Chapter 3
AU <$50 $10
$50 - $99 $20
$100 - $249 $50
>$250 $100
CA <$50 $5
$50 - $99 $15
$100 - $249 $30
>$250 $75
UK <$50 $20
$50 - $99 $25
$100 - $249 $55
$110
>$250
Using the information above, the student was successfully able to create
the program.
What do you think the student did?
This might be simple, but think this through and try to make this one as
pleasing as possible. If you wish to take on a bit of a challenge, add lists
and tuples to the mix to test yourself further.
Every program that you come across here can be done in hundreds of ways,
if not thousands. To me, the glass may seem half empty, and to you, it may
seem half full. It is completely based on how we analyze things and look at
them.
Put your thinking cap on, and for the next one, do not copy and paste the
code onto your PyCharm just yet. See if you can spot the issue with this
one.
Task-3: You are a programmer who has been tasked with creating a
simple yet intelligent game that stores a name that the users will have
to guess. Upon providing the wrong name, the program will provide
hints. You have created the following program; however, there seems to
be something wrong here.
name = 'James'
guess = input("I have a name. Can you try to guess it?: ")
guess_num = 0
max_guess = 5
while guess != name and guess_num == max_guess:
print(f"I am afraid, that's not quite right! Hint: letter {guess_num +1} ")
print(guess_num + 1, "is", name[guess_num] + ". ")
guess = input("Have another go: ")
guess_num = guess_num + 1
if guess_num == max_guess and name != guess:
print("Alas! You failed. The name was", name + ".")
else:
print("Great, you got it in", guess_num + 1, "guesses!")
Try not to jump to your IDE to figure this one out. First, take a moment or
two and analyze what is causing this program to end almost immediately
upon providing an incorrect name. Surely, there must be something that is
not right.
Read carefully between the code lines, and you should soon be able to
figure the matter out. Try and resolve the issue and then try the possible
solution on your IDE to see if it works.
Once again, I do encourage you to make things better by modifying the
code to your liking. There are hundreds of games you can come up with,
which are simple yet purely entertaining for others. As programmers, we
take pride in knowing that we were able to execute codes with efficiency
and ease. Programs will get more complex as you progress along in your
programming journey. For those interested in deep learning and machine
learning, expect hundreds of lines of code to train the machine. To do that,
you will need to be well-versed with almost every method in existence, all
the functions, and modules that are available across the internet to make the
most out of the experience.
Project - 2
Time for yet another project. Since we are discussing games, create a
Python program that lets the user know their astrological sign from the
given date of birth. The program may seem rather easy, but once you look
into the smaller details, you will soon realize that this will require you to
think a little out of the box.
For this project, I will not be providing hints nor a model to follow. You
already know, and you should be able to execute this one with ease and a bit
of finesse as well. You do not need any special modules or packages to get
this project done. All you need is a quick search on the internet to see which
star sign starts when to get you going.
Through trial and error, you should be able to create a program that can
work easily and exceptionally. Should you encounter issues, try and resolve
them on your own instead of looking for a solution on the internet.
If such projects interest you, you can find many more by searching for
“Python projects for beginners” and get started. The more projects you
work on, the better you will learn. Keep an eye out for what is in demand
these days and set your target to one day be able to carry out programming
of a level that will get you paid handsomely.
I wish this were a game where we could see who leads with how many
points and know who answered the questions correctly. However, we will
not let that get in the way of learning.
Answer as many questions as you can. To make this interesting, time
yourself and try to answer all the questions within 10 minutes. At the end of
the 10-minute mark, stop and review your answers to see where you stand.
Q-1: What does the == operator do?
A. It assigns a value
B. It recalls and matches the value of variables before and after it
C. It lets Python know not to equate variables
D. None of the above
Q-2: What is wrong with the code below?
x = 20
y = 30
z = 40
if x > y:
print("Something's wrong here")
A. Since x is less than y, the program will crash and return an error
B. z is not called; hence the program will not function
C. The condition is not followed by an indentation
D. There is nothing wrong with the program
Q-3: What will the result of the following program be?
alpha = 'Bravo'
bravo = 'Charlie'
charlie = 'Alpha'
for char in alpha:
if char != 'a':
print(char)
A. Bravo
B. Charlie
C. Alpha
D. None of the above
Q-4: What is the difference between 100 / 30 and 100 // 30?
A. It is just a typing mistake.
B. Both will deliver the same results.
C. The / will show a floating figure while the // will show an integer
remainder.
D. The / will show an integer remainder while the // a float remainder.
Q-5: What will the code shown below print as a result if a car is
traveling at 75 miles per hour?
car_speed = int(input("Enter Car's current speed: "))
acceleration = 20 #per second
top_speed = 100
time = 0 #in seconds
if car_speed == 0:
time = top_speed // acceleration
print(f"It should take {time} second(s) for the car to reach its top speed")
#For a stationary vehicle
else:
time = (top_speed - car_speed) // acceleration
print(f"it would take {time} second(s) to hit max speed.")
#For a vehicle in motion
A. 5 second(s)
B. 3 second(s)
C. 1 second(s)
D. The program will return an error
Q-6: When should you use a ‘for’ loop?
A. When we need one specific output
B. When we need to iterate over a range of elements
C. When we wish to set a certain condition to be either true or false
D. None of the above
Q-7: What does the following error indicate?
Traceback (most recent call last):
File "C:/Users/Programmer/PycharmProjects/PFB/PFB-2/Project-2.py",
line 1, in <module>
car_speed = int(input("Enter Car's current speed: "))
ValueError: invalid literal for int() with base 10: 'abc'
Process finished with exit code 1
A. The program crashed due to an invalid value entry
B. The program crashed as ‘abc’ was not entered as a string
C. Used single quotes instead of double quotes
D. None of the above
Q-8: The following program uses the log10 module from the ‘math’
package. The program was designed to carry out a few arithmetic
operations to test the values and functionality of the program. What
seems to be wrong here?
from math import log10
a = input("Enter 1st value: ")
b = input("Enter 2nd value: ")
print(a, "+", b, "is", a + b)
print(a, "-", b, "is", a - b)
print(a, "*", b, "is", a * b)
print(a, "/", b, "is", a / b)
print(a, "%", b, "is", a % b)
print(f"The base 10 logarithm of {a} is {log10(a)}")
print(a, "^", b, "is", a**b)
A. The strings are not formatted properly
B. The input values are stored as strings instead of integers
C. The log10 function will not work within a formatted string
D. All of the above
Q-9: What does an ‘elif’ statement do that ‘else’ can’t?
A. Elif conditions are secondary conditions that are executed when the
main condition is false
B. Elif statements do not require conditions whereas else statements do
C. Elif statements are exactly the same as else statements
D. None of the above
Q-10: What does the following produce as a result?
def high_number(numbers):
max = numbers[0]
for number in numbers:
if number < max:
max = number
return max
list = [21, 200, 31, 1, 39]
print(high_number(list))
A. 39
B. 5
C. 200
D. 1
Q-11: It is necessary to use ‘if’ statements every time you use loops. Is
this statement true or false?
And stop! Hopefully, you were able to do all of these within the time limit
of 10 minutes. I do not expect that this was an easy task as 10 minutes is not
exactly much, but then again, it was a challenge.
Well done for scoring as many as you did. The challenge wasn’t to see who
could get the most answers correct. It was actually designed to ensure you
continue practicing. Even if you were able to get one of these correct, using
your knowledge and not just a wild guess, it shows that you were paying
attention and trying to understand the problem to come up with a solution.
That is exactly the kind of attitude and commitment, which will take us
closer to success.
Take a break if you have been practicing for a while. It is said that a human
mind needs a quick minute or two to relax after every 45 minutes. You have
earned it. Once you are back, let us move ahead and try to analyze more
programs and see where people have gone wrong.
The objective of this section of the book is to reinforce the concepts related
to functions. To make this a little more interesting than others, I will be
providing you with scenarios to carry out on your own and convert into
fully functioning programs. You will be provided with a solution at the end.
All you need is to ensure you read the scenario and visualize it to sort out
what needs to go where, and then form a fully functional program.
From this point forward, I will be providing you with various scenarios,
each consisting of programs that you will need to create. Some of these may
require you to do a bit of research as well. However, if any special method,
library, module, or package is used, I will provide those within the
instructions.
Q-1: You are to create a function that calculates a taxi fare. The taxi
fare is comprised of a base fare of $3.00 and then $0.10 for every 100
meters traveled. Create a function that takes distance as its only
parameter (in km) and returns the value of the total applicable fare.
Follow up with a program to show the functioning nature of the
function.
The situation is rather easy. All you need is to work on the function and
work out the details accordingly. The rest will just fall into place
automatically. Take your time and process the information.
I know it is easy to be overwhelmed. A quick look at the internet will only
leave you confused. Take small steps and start somewhere. With time and a
bit of understanding, you will soon grasp the concept and be able to figure
out such situations easily.
The next one to come is even tougher. We have entered the phase where we
can say goodbye to the five to 10 line programs. It is best to let them go and
practice on bigger, more complex programs to polish your skills and make
yourself step out of your comfort zone and properly start exploring.
Q-2: A client has asked you to create a reusable program containing
reusable functions. The first situation is to create a function that
creates a virtual deck of playing cards.
Since there are 52 cards, the cards with numeric values from two to
nine will be represented by their respective numbers. For 10, Jack,
Queen, King, and Ace, you are required to use T, J, Q, K, and A.
Following the numeric/alphabetic value will be another character to
represent the suit. Use h for hearts, c for clubs, d for diamonds, and s
for spades.
You should create a function that does not take any parameter and uses
loops to iterate through all the cards and store them with a two-
character abbreviation in a list. The function should only return this
list as a result.
Hint: You will need to use the following as your beginning line.
from random import randrange
For this, expect quite a few lines of code. Your complete knowledge about
Python will be tested and tried in this one and the ones to come ahead.
There is no need to rush into things. If you are not able to do it the first time
around, you can do a bit of research and get some suggestions. I would
recommend not to jump to the solutions right away. Try and push your brain
to think a little outside the box. There is much to be learned, and the only
way it can be learned is to try.
Q-3: You have been asked by a colleague to help out with a Python
project. The assignment is to create a function that can generate a
random password for a user, which would contain between 6 to 8
characters at most.
For this, you will need to use the following:
from random import randint
shortest_pass = 6
max_pass = 8
min_ASCII = 33
max_ASCII = 126
The function should generate a random value from positions 33 to 126
of the ASCII table. This function will not take any parameters.
The above exercise will test you further and might even require a little
research on the ASCII table if you haven’t seen one before. It is always nice
to carry out a bit of research as it greatly helps us as a programmer to
further excel at what we do.
One of the toughest calls to make when creating a function is knowing the
right parameter you need to use to make the function work. You can use
almost any argument you pass through the parentheses to make it into a
parameter. Sometimes, you may not need a parameter at all, as we saw in
some of the exercises above. In such cases, it is best to leave the parameter
blank.
When in doubt, always consult the Python documentation to learn more
about the various parameters you can make use of when defining functions.
For recalling functions, hover your mouse over the parentheses, and a little
prompt should display the kind of parameters you can use with said
function.
The Solutions!
Finally, a chapter where you do not have to worry about solving exercises.
You have gone through every curveball, every scenario, and every exercise
provided within this workbook, and for that, you deserve the heartiest
congratulations. I am glad that you took your best shot at solving these
exercises.
For every programmer, the beginning is always the biggest hurdle. Once
you set your mind to things and start creating a program, things
automatically start aligning. Your brain automatically omits the needless
information through its cognitive powers and understanding of the subject
matter. All that remains then is a grey area that we discover further through
various trials and errors.
There is no shortcut to learn to program in a way that will let you type
codes 100% correctly, without a hint of an error, at any given time. Errors
and exceptions appear even for the best programmers on earth. There is no
programmer that I know of personally who can write programs without
running into errors. These errors may be as simple as forgetting to close
quotation marks, misplacing a comma, passing the wrong value, and so on.
Expect yourself to be accompanied by these errors and try to learn how to
avoid them in the long run. It takes practice, but there is a good chance you
will end up being a programmer who runs into these issues only rarely.
With that said, it is time to shift our focus back to the main part of this
chapter, the solutions to the never-ending exercises. Some of these were
incredibly simple, while others were not as simple as they sounded.
Regardless of how many you get right, you should never be afraid of nor let
down by failure. It is a part of our learning cycle and should be accepted,
understood, and then corrected. The more you learn from your mistakes, the
easier things will be in the future.
Chapter by Chapter Solutions
Chapter 1 Solutions
Below are the answers, and the correct answer applicable to the question is
highlighted in bold text.
Q-1: The question asked to identify which of the codes mentioned used
Python as its programming language.
● Code 1: Unity C# - We do not use the statement ‘using’ in Python,
nor do we use semicolons at the end.
● Code 2: HTML – The second language in the list used HTML,
which is used for developing websites.
● Code 3: Python – Evident from the import statement and the
missing semicolon.
● Code 4: JavaScript – Similar to C# but with a few differences.
Q-2: How can you check if your system has Python 3.8.x installed on
your system? Let’s see what the correct method is to check for the same:
A. PyCharm – PyCharm is an IDE and can be installed without having
Python onboard.
B. Command on PyCharm – The given command will not work on
PyCharm.
C. Command on console/terminal – This is the correct method to
locate the version of python.
D. The website will not indicate the version you have installed.
Q-3: What is the language named after? This was related to the history
that we covered in the previous book. If you got this wrong, it is okay. The
correct answer is A. The language was named after the famous Monty
Python’s flying circus.
Q-4: How does each line in Python end? To be honest, this was one of the
easiest questions. But surprisingly, people still tend to forget.
A. With a colon ‘:’
B. With a semicolon ‘;’
C. With a full-stop/period ‘.’
D. None of the above – Because every line in Python ends without
any special character except when defining conditions or
functions.
Q-5: What does the acronym IDE stand for? We have discussed this in
the previous book.
A. International Day for Electronics
B. Integrated Developing Environment
C. Integrated Developer Environment
D. Integrated Developing Engineering
Q-6: How is a string represented in Python?
A. With a single quotation mark ‘’
B. With a double quotation mark “”
C. With either of the above. – We can create strings using single or
double quotation marks.
D. None of the above.
Q-7: What is a variable? Once again, an easy question.
A. It’s a function in Python.
B. It’s a method in Python.
C. A user-created container holding immutable values is close but not
exactly the right answer as variables can change.
D. It’s a user-created container holding values that can be
modified.
Q-8: How would you print a string that says He said, “Yes!”?
A. print(“He said, “Yes!”)
B. print(f“He said, “Yes!”)
C. print(‘He said, “Yes!”’) – Using double quotation marks would
end the string at the start of “Yes”
D. print(He said, Yes!)
Q-9: Running the code as shown, what will the output be?
num = '5' * '5'
print(num)
A. 25
B. 5, 5, 5, 5, 5
C. ‘5’ * ‘5’
D. TypeError: Can’t multiply sequence by non-int of type ‘str’ – A
string cannot be multiplied by another string.
Q-10: If you run a code that ends up with an error, it will cause
PyCharm to crash.
A. True
B. False – PyCharm is a safe working environment that is designed
to test codes. If the code will crash, the IDE returns the error
code to inform users that this will crash when used outside
PyCharm.
C. Depends on the type of code written
D. None of the above
Q-11: Which is the correct method to set the value for a bool
‘is_married’?
A. “True”
B. True
C. ‘True’
D. true
Q-12: Which of the following is a formatted string?
Code-1:
name = "Jiovanni"
age = 41
print("Hi, I am naming, and I am age years old")
Code-2:
name = "Jiovanni"
age = 41
print(f"Hi, I am {name} and I am {age} years old")
This is the correct way to format a string. There are other ways you can
format strings, but I find this a lot easier.
Code-3:
name = "Jiovanni"
age = 41
print("Hi, I am " + name + " and I am " + age + " years old")
Code-4:
name = "Jiovanni"
age = 41
print("Hi, I am [name] and I am [age] years old")
Q-13: To name a variable called the first name, which method is
correct? You can choose more than one answer to the following
question.
A. firstname
B. FirstName
C. first.name
D. first_name
If you are surprised about the second entry here, remember that it is
recommended not to use this format to name variables. While it is not
recommended, it does not mean that it is wrong.
Q-14: Choose one or more answers which apply. Clean-code practice is:
A. To keep our workstations clean.
B. To name our variables and functions appropriately
C. To improve readability.
D. To ensure the code is not breaking any laws.
Q-15: Which of the following is the correct way to create a variable
named ‘test’:
A. def test():
B. test.create
C. test = “” – You can always create variables as blanks
D. print(test)
Q-16: What is a concatenation of strings?
A. To merge two or more strings into a new string object
B. To separate two strings
C. To convert an integer into a string
D. None of the above
Q-17: Choose the correct answer(s). Python is:
A. The successor of the ABC language – This was discussed in the
previous book.
B. Only operable through PyCharm IDE
C. Used for automation and Machine Learning – These are two of
the most in-demand fields of modern times.
D. All of the above
Q-18: What is OOP?
A. Object-Oriented Python
B. Object-Oriented PyCharm
C. Object-Oriented Programming – Remember, everything in
Python is considered an object.
D. Only On Python
Q-19: How can you acquire user input and store it in a variable called
income, for calculation purposes?
A. income = bool(“Enter your income:”)
B. income = int(“Enter your income:”)
C. income = input(“Enter your income:”)
D. income = int(input(“Enter your income:”) – The user will input
a value that will be then converted into an integer.
Q-20: Which of these is/are true regarding Python?
A. There are two data types
B. Variables can be called, modified, or removed.
C. Python can work without PyCharm
D. Python is a case-sensitive language
Yes! Python can work without PyCharm as PyCharm is just one of the
many ways to operate Python and write codes.
Is This Correct? – Part 1 Solutions
This was indeed a section that caused quite a bit of confusion but provided
the perfect opportunity to practice our coding skills and keep an eye out for
errors. Let us look at the solutions to the questions posed within the first
part of the “Is This Correct?” series.
Chapter 2 Solutions
Chapter 3 Solutions
Chapter 4 Solutions
References
ggs, J, R. (2013): Python For Kids. San Francisco, CA: No Starch Press
atthes, E. (2016): Python Crash Course. San Francisco, CA: No Starch Press
yne, B. (2015): Teach Your Kids to Code. No Starch Press
ogramiz. (n.d.). Python Program to Check Leap Year. Retrieved December
10, 2019, from https://www.programiz.com/python-
programming/examples/leap-year.
phenson, B. (2014): The Python Workbook. Springer International
Publishing