Python For Beginners. 2 Books in 1 - A Completed Guide To Master The Basics of Python Language
Python For Beginners. 2 Books in 1 - A Completed Guide To Master The Basics of Python Language
Getting Started
Programming is becoming an increasingly demanded skill for anything from
web design to Machine Learning and the Internet of Things.
It’s on its way to having daily use due to the importance of technology.
While programming used to be a subject that people started studying for their
computer science degree, now it is often taught starting from elementary
school.
One of the main reasons for its widespread use is accessibility.
You don’t need much to get started.
Thanks to the Internet's power, all you need is a computer and a number of
software tools that you can download and install without spending a penny.
In addition, there are many resources to learn from, as well as organized
communities you can join and learn from.
In this chapter, you are going to learn why Python is one of the best
programming languages to start with, as well as progress your career if this
isn’t your first language.
Furthermore, you will explore the tools you need, install them, and start your
journey.
This chapter will guide you step by step and show you everything you need
to know in order to get started.
If you are already familiar with any other programming language such as C,
C++, or Java, you might want to skip this chapter or simply glance through it
to refresh your memory.
We can define programming as the process of designing, coding, debugging,
and maintaining the source code of a computer program, which means that
we say the steps to follow for the creation of the source code of computer
programs.
The programming language is all the rules or regulations, symbols, and
particular words used for the creation of a program, and with it, offer a
solution to a particular problem.
The best-known programming languages are Basic (1964), C++ (1983),
Python (1991), Java (1995), C# (2000), among others.
Programming is one of the stages for software development; programming
specifies the structure and behavior of a program, verifying if it is working
properly or not.
Programming includes the algorithm's specification defined as the sequence
of steps and operations that the program must perform to solve a problem; for
the algorithm to work, the program must be implemented in a compatible and
correct language.
We could consider programming even easier than learning a new language
because the programming language will be governed by a set of rules, which
are, generally, always similar, so you could say that it might be considered a
natural language.
In order to better understand the subject of programming, we could start with
the beginnings of programming and how all this universe of languages and
programs we know today began.
We could start by saying that programming began when the first computer
was created in the fifteenth century when a machine capable of doing basic
operations and square roots appeared (Gottfried Wilhelm von Leibniz).
However, the one that actually served as a great influence for the creation of
the first computer was the differential machine for calculating polynomials
with the support of Lady Ada Countess (1815-1852), known as the first
person who entered programming and from whom comes the name of the
programming language ADA, created by the DoD (Department of the United
States), in the 1970s.
Initially, it was programmed in binary codes (bi=2), in other words, it
consists of strings of 0s and 1s, which is the language directly understood by
the computer, or what is known as machine language, a language considered
fundamental for the commuter to be thus capable of interpreting the
information supplied.
Later the languages of high level appeared, using English words to give
orders to follow, using intermediate processes between the language and the
computer, this process can be a compiler or an interpreter.
The syntax of these programming languages is much simpler than our
languages, and they use a much smaller vocabulary and set of rules.
In summary, we could say that programming is a set of sentences written in a
programming language that tells the computer what tasks to perform and in
what order through a series of instructions that fully detail the process.
In the world of programming languages, we find interpreted languages, such
as javascript, where a program called interpreter executes the sentences while
reading the text file where they are written, which is why these programs are
often also called scripts.
On the other hand, we have compiled languages such as Java. In this case, we
must previously convert the text file to a ¨translation¨ through a program
called ‘compiler’ and the resulting file is the one that will finally run on the
computer.
In this book, we will speak specifically of the Python programming language,
being this an interpreted language whose main and most important
characteristic is the application of a syntax that favors the application of
readable code.
We could say that the interpreter is a type of program that executes code
directly, that is to say, it does not need to be compiled, and that is the case of
our target language.
What Is Python?
Python is one of the most important programming languages nowadays,
being a general-purpose language.
In this book, you will have the language base so that you can start with it.
With this language, you can create a huge and varied number of applications
because it allows you to create different applications since it doesn't have a
defined purpose.
Why Python?
Python is a versatile and powerful programming language that was developed
in 1991 by Guido van Rossum.
As a fun fact, you should know that the name of the language doesn’t come
from the snake, which bears the same name.
Guido named his project “Python” after Monty Python, which was a British
comedy group he was a big fan of.
If you happen to be a fan as well, you will find several “Easter Eggs” within
the official documentation of the language.
Since 1991, Python has been used to introduce people to programming due to
its simple syntax, as well as to create complex programs or analyze massive
amounts of data.
As a beginner with Python, you will be able to write a basic program quickly.
However, you can easily scale it further and turn it into a commercial project.
The main reason why Python is so popular for beginners is the fact that the
language is easy to read and write.
Its structure is human-like and easy to understand; therefore, the code is very
user-friendly.
This means that you shouldn’t find it too difficult to remember the language
and structure.
In addition, Python comes with a number of libraries and premade functions
that you can immediately add to your code.
This way, you can save time.
In many ways, it’s like playing with Legos.
As long as you pace yourself, learn and practice everything in this book, and
extend your knowledge using other resources, you will be able to write a
program that you will understand ten years from now.
Program maintenance is a crucial part of your responsibilities as a
programmer, but luckily Python code is easy to administrate compared to
other languages.
With that in mind, let’s briefly explore the plethora of reasons why you
should learn Python instead of any other languages.
After all, Python isn’t quite the only language that offers you the advantages
you’ve learned about so far.
User-friendly: the purpose of a programming language is to form
the connection between humans and computers.
Python, like C# and Java, is a high-level programming language,
which means that it is quite far from the machine language which
the computer then processes.
The opposite of this is the low-level language, which usually refers
to assembly language or machine code.
In other words, Python is close to English.
This allows you to write code as fast as you write any sentence,
once you learn the rules and the syntax.
Powerful: sometimes, Python is looked down upon because it is so
easy to learn and it’s usually the first language programmers
explore, whether on their own or at computer science 101.
However, Python is a very powerful language that is just as
versatile and efficient as more complex languages such as C++.
Python is used in every technical department in companies like
Google, Microsoft, IBM, Xerox, NASA, and many more.
You can even use Python in game development if you prefer to
practice a programming language in a more artistic way.
OOP: Object-oriented programming is many times the optimal
computer problem solver.
It is a methodology that offers a method of defining data and
actions as objects.
This type of programming is not always necessary; however, it is
usually the most optimal approach when working on large
applications.
For instance, programming languages such as C# and Java are
object-oriented.
Python can be considered an object-oriented language as well, but
this feature is optional.
The other languages don’t offer such versatility.
This means that with Python, you don’t necessarily have to learn
the object-oriented methodology from the start.
This is one of the reasons why it’s so much easier to start
programming with Python than C++.
However, you have the massive benefits of OOP at your fingertips,
but only when you actually need it.
If you are working on a basic program, there’s no need for it.
Python offers you all the power and versatility you need.
Computer-friendly: you can run Python on any kind of computer.
You don’t need a powerful computer processing unit and a great
deal of RAM to start programming.
You can even use a credit-card-sized computer like the Raspberry
Pi.
In fact, Python requires so little that it is one of the top languages
used in creating little robots that are operated by $5 computers.
In addition, Python runs on any operating system, whether it’s
Linux, Windows, or Mac.
The programs you write do not depend on the platform.
You can work on an application on your Windows running
computer and then switch it to your Mac.
For instance, if you finished creating a program and you need beta
testers, you can email your project to a friend that uses Linux and
another one with Windows. The program will work.
Language adaptability: if you ever write a program in another
language, you can integrate Python within it.
In other words, you can use Python on a program that was written
in Java.
In addition, you also combine Python with another language in
order to take advantage of the benefits that are offered by both of
them.
For instance, you can integrate C or C++ in order to benefit from
the system optimization and speed that they offer.
It’s free: everyone likes free stuff, and Python won’t cost you a
cent.
You can always download and install it for free as many times as
you want.
In addition, Python is an open-source language, which means that
the license even allows you to make modifications to the source
code.
This means that you can modify Python and then sell your own
version of it.
You might not be interested in these features at this point, but it is
one of the reasons why it’s such a popular language.
Community: being a powerful and versatile open source
programming language brings benefit to the community.
There are many online communities dedicated to teaching and
learning everything there is to know about Python.
You can ask questions on online boards or seek the advice of a
master programmer.
You can also seek fellow students and work on a project together.
Python’s popularity has gathered a massive crowd around it, and
you should take advantage of it.
Installing Python
Before you can start programming, you need to download and install Python
on your machine.
The installation is quite straightforward no matter what operating system
you’re running; however, you do need to pay attention to a couple of things.
First, you need to head to Python’s homepage and head to the “Downloads”
section.
There you will see a number of different installers, and each one of them has
a different version.
Make sure to download the right installer that matches your computer’s
operating system and select the latest version.
Once the download is complete, run the installer and follow the steps.
You should simply accept the standard settings, and once the installation is
complete, you’re ready to go.
If you don’t want to install Python for some reason, you may notice that you
have some kind of a console on the website's homepage.
This is a Python online console, and you can use it to practice your coding
skills or to try out some of the examples in this book.
It’s advisable for you to type the code yourself, even if you copy it from the
book, and then try to be creative with it.
You need to practice in order to memorize the syntax and specific commands,
and the online console is really handy for a quick practice session.
Using a Text Editor
Python programming can be done with nearly any kind of plain text editor.
You can use programs like Notepad, Notepad++, gedit, and many more.
Keep in mind that some of these text editors come with a variety of features
that are useful to programmers.
For instance, some of them, such as Notepad++ offer syntax highlighting
which will instantly show you any errors you made.
If you type code in a basic editor like plain Notepad, the program won’t tell
you when you’ve forgotten a semicolon or if you added additional space.
There are many programs to choose from, so pick any editor you feel
comfortable with.
With that in mind, avoid using word processors such as Microsoft Word or
Open Office.
They aren’t good for programming purposes.
They can be used to write code; however, the problem is that when saving it,
the program will sneak in some additional lines of code by itself.
That code is specific to the word processor, and it can impact your program’s
speed, or even worse, it will simply not run.
Using an IDE
An IDE, which stands for Integrated Development Environment, is a program
designed with a number of features that are useful to programmers.
It has a graphical interface, and it makes typing code much faster due to
autocomplete and history functions.
Programming stays the same whether you are using a text editor or an IDE.
However, with the IDE, you will benefit from many shortcuts, reminders,
error signaling, and code autocorrect.
Many IDE’s even include suggestions on how to fix an error.
There are many IDE’s to choose from, but one of the most popular ones is
IDLE.
It comes in the same package as Python, so there’s no need to perform any
extra steps.
Keep in mind that it can run in two modes, namely interactive and script.
Use interactive if you want Python to respond to whatever commands you
type immediately.
Your First Program
Now that your toolkit is prepared, it’s time to write your first program.
For this example, we’ll use IDLE because it’s important to get used to IDE’s
from the start in order to avoid any future frustrations.
If you prefer to use a text editor or the online Python console, go ahead, the
code will work the same.
Now, start running IDLE in interactive mode.
You will now see a window that is known as a Python shell.
At the command prompt, type the following line:
print (“Hello World!”)
Now you should see the result displayed on your screen like the following:
Hello World!
That’s it!
Congratulations, you can call yourself a programmer now.
Now let’s discuss this bit of code briefly.
The first thing you’ll notice is that Python code is plain English, easy to read
and understand.
Even without programming knowledge, you probably knew what this line of
code would do because it’s self-explanatory.
That’s the beauty of working with Python.
As for the command we used, “print ()” is a function that displays the text
which is written in the parentheses.
Keep in mind that the line needs to be surrounded by quotation marks;
otherwise, you’ll get an error.
Furthermore, pay attention to how you type the function because, in Python,
everything is case sensitive.
The command “print” will work. However, if you type it as “Print,” it will
not.
Now, let’s create the same program but this time by using IDLE’s script
mode.
Don’t forget that interactive mode gives you instant results.
It works the same as the online Python shell.
However, you won’t be able to save your program so that you can continue
working on it later.
In order to save it and edit it later, you need to work in script mode.
You can run IDLE in script mode simply by clicking on “File” and selecting
“New Window.”
Now type the same line again:
print (“Hello World!)
Hit the Enter key.
You’ll notice that nothing happens.
That’s because you are writing a list of instructions that will be executed at a
later date when you run the program.
First, you need to save the application by clicking on “Save As” from the
“File” menu.
You’ll notice that by default, the file has the “py” extension.
Always make sure your scripts are saved this way in order to be recognized
as Python programs.
Now, if you run the program, IDLE will open the interactive mode window
and display the result.
For now, you’ve run your “Hello World” program by using IDLE.
However, you normally want your applications to run like the ones you are
currently using.
This means you want an executable file that you double click and it runs.
At the moment, if you click on the Python file, a window will open and then
close abruptly.
You may be thinking that the program doesn’t work because nothing
happened; however, something did happen.
It was simply too fast for you to observe anything concrete.
The program executed all of its instructions, which means that it displayed
the message in a fraction of a second, and then it terminated itself.
What you need to do is keep the program running once it executes all of its
commands so that you can see the results and interact with them.
But before you do that, let’s take a moment to discuss how to comment on
your code and make it readable and easy to understand.
Code Comments and Your Program
Open your script and type the following lines:
# Hello World!
# This is a demonstration of the “print” function.
If you run the program again, you will see that nothing changed.
These lines you added aren’t executed as code.
They are known as comments, and their purpose is to make the code of an
application more understandable.
You might be thinking that typing such information is a waste of time
because, as the programmer, you already know what your code is about.
That may be true; however, when you write a complex program, and then you
abandon it for a week or two, you’re going to have some trouble
understanding the purpose of every function and variable.
Sure, you can read your code and eventually figure everything out, but that is
not the proper use of your time.
Code comments are used to label and explain complicated functions so that
you don’t have to dive into the code itself.
They are especially useful if another programmer is going to work on your
program at a later date.
Imagine a stranger having to decipher your personal approach to the
development of your application.
On a large project, he could waste wakes of his time instead of doing some
work in order to progress.
Comments are defined by the hash mark in front of a line.
Each line you intend as a comment needs to have its own mark; otherwise,
you will get an error.
If you’re worried about your programs' efficiency due to hundreds or even
thousands of comments, you shouldn’t be.
They have no impact on your computer because when the code is executed,
the machine ignores all comments and uses no additional resources.
Additionally, to make your comments and code more readable, you can leave
empty lines.
However, don’t do this after every line of code.
Use an empty space in between blocks of code or sections.
Programs ignore blank space, so nothing will be affected by using it.
Now let’s get back to your first program.
Add the following line after the print function:
input (“\n\n Hit the Enter key to exit!”)
This line will display the console in which the line “Hello World!” is printed
and then display the line “Hit the Enter key to exit!”
Finally, the program will stay open and wait for you until you hit the Enter
key.
This is a simple way to keep the program running until the user performs an
action.
Chapter 2. Data Types in Python
Every program has certain data that allows it to function and operate in the
way we want.
The data can be a text, a number, or any other thing in between.
Whether complex or as simple as you like, these data types are the cogs in a
machine that allow the rest of the mechanism to connect and work.
Python is a host to a few data types, and, unlike its competitors, it does not
deal with an extensive range of things.
That is good because we have less to worry about and yet achieve accurate
results despite the lapse.
Python was created to make our lives, as programmers, a lot easier.
Strings
In Python and other programming languages, any text value that we may use,
such as names, places, 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, the 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 type 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
Process finished with exit code 1
Here’s a hint: That’s an error!
So what happened here?
Try and revisit the inputs.
See how we started the first print statement with a single quote?
Immediately, we ended the quote using another quotation mark.
The program only accepted the letter ‘I’ as a string.
You may have noticed how the color may have changed for every other
character from ‘m’ until ‘won,’ after which the program detects yet another
quotation mark and accepts the rest as another string.
Quite confusing, to be honest.
Similarly, in the second statement, the same thing happened.
The program saw double quotes and understood it as a string, right until the
point the second instance of double quotation marks arrives.
That’s where it did not bother checking whether it is a sentence or that it may
have still been going on. Computers do not understand English; they
understand binary communications.
The compiler is what runs when we press the run button.
It compiles our code and interprets the same into a series of ones and zeros so
that the computer may understand what we are asking it to do.
This is exactly why the second it spots the first quotation mark, it considers it
as a start of a string and ends it immediately when it spots a second quotation
mark, even if the sentence was carrying onwards.
To overcome this obstacle, we use a mixture of single and double quotes
when we know we need to use one of these within the sentence.
Try and replace the opening and closing quotation marks in the first state as
double quotation marks on both ends.
Likewise, change the quotation marks for the second statement to single
quotation marks as shown here:
print("I'm afraid I won't be able to make it")
print('He said "Why do you care?"')
Now the output should look like this:
I'm afraid I won't be able to make it
He said, "Why do you care?"
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 that 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 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.
As we programmers refer to as containers, these special vehicles are called
‘variables,’ and they are the elements that 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 if 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 = "James"
age = 43
height_in_cm = 163
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.
To print that to the console, we will do this:
print(name)
Output
James
The same goes for 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)
Surprised? Did you end up with this?
print(name age height_in_cm occupation)
^
SyntaxError: invalid syntax
Process finished with exit code 1
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:
James 43 163 Programmer
“Your variables, Sir!”
And now, it knew what we were talking about.
The system recalled these variables and was successfully able to show us
what their values were.
But what happens if you try to add two strings together?
What if you wish to merge two separate strings and create a third-string as a
result?
first_name = “John”
last_name = “Wick”
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 to
convert the integer into a string first 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
You may wish to remember this as we will be visiting the conversion of
values into strings a lot sooner than you might expect.
There is one more way through which you can print out both string variables
and numeric variables, all at the same time, without the need for ‘+’ signs or
conversion.
This way is called String Formatting.
To create a formatted string, we follow a simple process as shown here:
print(f“ This is where {var 1} will be. Then {var 2}, then {var 3} and so
on”)
Var 1, 2, and 3 are variables.
You can have as many as you like here.
Notice the importance of whitespace.
Try not to use the spacebar as much.
You might struggle at the start but will eventually get the hang of it.
When we start the string, we place the character ‘f’ to let Python know that
this is a formatted string.
Here, the curly brackets are performing a part of placeholders.
Within these curly brackets, you can recall your variables.
One set of curly brackets will be a placeholder for each variable that you
would like to call upon.
To put this in practical terms, let’s look at an example:
show = "GOT"
name1 = "Daenerys"
name2 = "Jon"
name3 = "Tyrion"
seasons = 8
print(f "The show called {show} had characters like {name1}, {name2} and
{name3} in all {seasons} seasons. ")
Output:
The show called GOT had characters like Daenerys, Jon, and Tyrion in all 8
seasons.
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 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 the users for using the
form and that they will be contacted at 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: ")
print(f"Thank you very much {name}, you will be contacted at {email}.")
Output:
Hello and welcome to my interactive tutorial.
Your Name: Sam
Your age: 28
Where do you live? London
Please enter your email address: [email protected]
Thank you very much Sam, you will be contacted at [email protected].
In the above, we began by printing a greeting to the user and welcoming them
to the tutorial.
Next, we created a variable named ‘name’ and assigned it a value that our
user will generously provide us with.
In the age, you may have noticed I changed the input to int(), just as we
changed integer to string earlier on.
This is because our message within the input parameters is a string value by
default, as it is within quotation marks.
You will always need to ensure you know what type of value you are after
and do the needful, as shown above.
Next, we asked for the name of the city and the email address.
Now, using a formatted string, we printed out our final message.
“Wait! How can we print out something we have yet to receive or know?”
I did mention that Python works line by line.
The program will start with a greeting, as shown in the output.
It will then move to the next line and realize that it must wait for the user to
input something and hit enter.
This is why the input value has been highlighted by bold and italic fonts here.
The program then moves to the next line and waits yet again for the user to
put something in and press enter, and this goes on until the final input
command is sorted.
Now the program has the values stored; it immediately recalls these values
and prints them out for the viewer to see in the end.
The result was rather pleasing as it gave a personalized message to the user,
and we received the information we need.
Everybody walks away, happy!
Storing information directly from the user is both essential and, at times,
necessary.
Imagine a game that is based on Python.
The game is rather simple, where a ball will jump when you tap the screen.
The problem is, your screen isn’t responding to the touch at all for some
reason.
While that happens, the program will either keep the ball running until an
input is detected, or it will just not work at all.
We also use input functions to gather information such as login ID and
passwords to match with the database, but that is a point that we shall discuss
later when we will talk about statements.
It is a little more complicated than it sounds now, but once you understand
how to use statements, you will be one step closer than ever before becoming
a programmer.
Chapter 3. Operators - The Types and Their
Uses
Example
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
def welcome(salute):
"""The Python function welcomes you to
the individual passed in as
parameter"""
print("Welcome " + salute + ". Lovely Day!")
Calling a Function in Python
We can call a function once we have defined it from another function or
program.
Calling a function simply involves typing the function name with suitable
parameters.
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
welcome(‘Brenda’)
The output will be “Welcome Brenda. Lovely Day!’
Practice Exercise
Write a function that when called outputs “Hello (student name), kindly
submit your work by Sunday.”
Docstring
It is placed after the function header as the first statement and explains in
summary what the function does.
Docstring should always be placed between triple quotes to accommodate
multiple line strings.
Calling/Invoking the docstring we typed earlier
Example
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
print(welcome._doc_)
The output will be “This function welcomes you to
the individual passed in as
parameter”.
The syntax for calling/invoking the docstring is:
print(function_name. _doc_)
Python Function Return Statement
Return syntax
return [list of expressions]
Discussion
The return statement can return a value or a None object.
Example
Print(welcome(“Richard”)) #Passing arguments and calling the function
Welcome, Richard. Lovely Day!
None #the returned value
Random Function in Python
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
import math
print(random.shuffle_num(11, 21))
y=[‘f’,’g’,’h’,’m’]
print(random.pick(y))
random.anypic(y)
print(y)
print(your_pick.random())
Iterators
In Python, iterator refers to objects that can be iterated upon.
The for loop is used to implement iterators in Python anywhere.
Iterators in Python can also be implemented using generators and
comprehensions.
In Python, an iterator concerns a construct that can be called several times
performing the same action.
Iterators in Python implement the _iter_() special method and _next_()
special method, which is collectively referred to as the iterator protocol.
In Python, an object becomes iterable if we can get an iterator from it, for
example, string, tuple, and the list is iterable.
In operation, the iter() function calls the _iter_() method and returns an
iterator from the set or list or string.
Manually Iterating Through Items in Python
The next() function is used in Python to manually loop through all the items
of an iterator
Example
list_mine = [14, 17, 10, 13]
iter_list = iter(list_mine)
print(next(iter_list))
print(next(iter_list))
print(my_iter.__next__())
print(my_iter.__next__())
next(iter_list)
NOTE
The for loop provides an efficienty ay of automatically iterating through a
list.
The for loop can be applied on a file, list or string among others in Python.
Example
for element in list_mine:
print(element)
Explaining the Loop
The for loop gets to iterate automatically through the Python list.
Example
for element in list_mine:
object_iter = iter(iterable)
while True:
try:
element = next(object_iter)
except StopIteration:
break
Creating Custom Iterator in Python
On the other hand, the _next_() will scan and give the next element in the
sequence and will trigger the StopIteration exception once it reaches the end.
Example
class Power:
"""Will implement powers of 2
"""
def __init__(self, max = 0):
self.max = max
def __iter__(self):
self.m = 0
return self
def __next__(self):
if self.m <= self.max:
result = 2 ** self.m
self.m += 1
return result
else:
raise StopIteration
Discussion
Example
for j in Power(5):
print(j)
Infinite Iterators
There may be situations that require continuous iteration.
The situations we have tackled so far were infinite iterators and had to
terminate after exhausting the items in the iterable.
The iter() is an inbuilt function.
The method is fired by providing two arguments.
The first argument in iter() is the one being called while the other argument
acts as a sentinel.
Until the function returns a value equal to the Sentinel, the iterator will
continue calling the function.
Example
int()
infer = iterate(int,2)
next(infer)
next(infer)
Discussion
The int() function in this program will always return value 0.
Therefore, passing the function as iterate(int, 2) will return an iterator that
invokes int().
The calling of int() will stop when the returned value equals 2.
Since this will never happen, we will end up with an infinite iterator.
Example
Assume we want to display all odd numbers that exist.
Practice Exercise
Write a Python program that uses a custom infinite iterator to display all even
numbers.
Closure Function in Python
Example
def printing(msg):
def printers():
print(msg)
return printer
custom = printing("Welcome")
custom()
Discussion
The printing() function was invoked with the string “Welcome” that gives us
objects associated with the name.
Calling custom() implied the message was remembered even though it had
already completed executing the printing() function.
In Python, the technique via which part of the data gets tied to the code is
termed closure.
In this case, even when the variable gets out of scope, the value in the
enclosing scope is remembered.
Example
del printing
another()
printing("Welcome")
NOTE
In Python, closures help provide a limited form of encapsulation.
The use of enclosures can help avoid the wide usage of global scope
variables.
Remember, global scope implies that the names are accessible and modifiable
at any part of the program, which can create inconsistency.
Closures can also be used to give an object-oriented solution to a problem.
Example
def product(n):
def times(y):
return y* number
return times
multiply1 = times(13)
multiply1 = times(15)
print(multiply2(19))
print(multiply2(13))
print(multiply2(multiply(12)))
Projects - Implementing Simple Calculator in Python
def sum(m, n):
return m + n
def minus(m, n):
return m - n
def product(m, n):
return m * n
def division(m, n):
return m / n
print("Choose an Operation.")
print("1.Sum")
print("2.Minus")
print("3.Product")
print("4.Division")
option = input("Type your choice (1/2/3/4):")
number1 = int(input("Enter number 1: "))
number2 = int(input("Enter number 2: "))
if option == '1':
print(number1,"+",number2,"=", sum(number1,number2))
elif option == '2':
print(number1,"-",number2,"=", minus(num1,num2))
elif choice == '3':
print(number1,"*",number2,"=", product(number1,number2))
elif choice == '4':
print(number1,"/",number2,"=", division(number1,number2))
else:
print("Check Your Selection, Out of Range")
Program to return factors of any integer
def factors(m):
print("We found factors of",m,"as:")
for j in range(1, m + 1):
if m % j == 0:
print(j)
number = 400
factors(number)
Chapter 5. Exception Handling
What Is Exception Handling?
Exception handling is error management.
It has three purposes:
It allows you to debug your program.
It allows your program to continue running despite encountering an
error or exception.
It allows you to create your customized errors that can help you debug,
remove, and control some of Python’s nuances and make your program
function as you want it to.
Handling the Zero Division Error Exception
Exception handling can be an easy or difficult task depending on how you
want your program to flow and your creativity.
You might have scratched your head because of the word creativity.
Programming is all about logic, right? No.
The core purpose of programming is to solve problems.
A solution to a problem does not only require logic.
It also requires creativity.
Have you ever heard of the phrase, “Think outside of the box?”
Program breaking exceptions can be a pain, and they are often called bugs.
The solution to such problems is often elusive.
And you need to find a workaround or risk rewriting your program from
scratch.
For example, you have a calculator program with this snippet of code when
you divide:
>>> def div(dividend, divisor):
print(dividend / divisor)
>>> div(7, 0)
Traceback (recent call to come last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in div
ZeroDivisionError: division by zero
>>> _
Of course, division by zero is an impossible operation.
Because of that, Python stops the program since it does not know what you
want to do when this is encountered.
It does not know any valid answer or response.
That being said, the problem here is that the error stops your program
entirely.
To manage this exception, you have two options.
First, you can make sure to prevent such an operation from happening in your
program.
Second, you can let the operation and errors happen, but tell Python to
continue your program.
Here is what the first solution looks like:
>>> def div(dividend, divisor):
if (divisor != 0):
print(dividend / divisor)
else:
print("Cannot Divide by Zero.")
>>> div(5, 0)
Cannot Divide by Zero.
>>> _
Here is what the second solution looks like:
>>> def div(dividend, divisor):
try:
print(dividend / divisor)
except:
print("Cannot Divide by Zero.")
>>> div(5, 0)
Cannot Divide by Zero.
>>> _
Remember the two core solutions to errors and exceptions.
One, prevent the error from happening.
Two, manage the aftermath of the error.
Using Try-Except Blocks
In the previous example, the try-except blocks were used to manage the error.
However, you or your user can still do something to screw your solution up.
For example:
>>> def div(dividend, divisor):
try:
print(dividend / divisor)
except:
print("Cannot Divide by Zero.")
>>> div(5, "a")
Cannot Divide by Zero.
>>> _
The statement prepared for the “except” block is not enough to justify the
error that was created by the input.
Dividing a number by a string does not actually warrant a “Cannot Divide by
Zero.” message.
For this to work, you need to know more about how to use except block
properly.
First of all, you can specify the error that it will capture and respond to by
indicating the exact exception.
For example:
>>> def div(dividend, divisor):
try:
print(dividend / divisor)
except ZeroDivisionError:
print("Cannot Divide by Zero.")
>>> div(5, 0)
Cannot Divide by Zero.
>>> div(5, "a")
Traceback (most recent call last):
File "<stdin>", line 1, <module>
File "<stdin>", line 3, in div
TypeError: unsupported operand type(s) for /: 'int' and 'str'
>>> _
Now, the error that will be handled has been specified.
When the program encounters the specified error, it will execute the
statements written on the “except” block that captured it.
If no except block is set to capture other errors, Python will then step in, stop
the program, and give you an exception.
But why did that happen?
When the example did not specify the error, it handled everything.
That is correct.
When the “except” block does not have any specified error to look out for, it
will capture any error instead.
For example:
>>> def div(dividend, divisor):
try:
print(dividend / divisor)
except:
print("An error happened.")
>>> div(5, 0)
An error happened.
>>> div(5, "a")
An error happened.
>>> _
That is a better way of using the “except” block if you do not know exactly
the error that you might encounter.
Reading an Exception Error Trace Back
The most important part in error handling is to know how to read the trace-
back message.
It is fairly easy to do.
The trace-back message is structured like this:
<Traceback Stack Header>
<File Name>, <Line Number>, <Function/Module>
<Exception>: <Exception Description>
Here are things you need to remember:
The traceback stack header informs you that an error occurred.
The filename tells you the name of the file where the fault is
located.
Since the book's examples are coded using the interpreter, it always
indicated that the file name is "<stdin>" or standard input.
The line number tells the exact line number in the file that caused
the error.
Since the examples are tested in the interpreter, it will always say
line 1.
However, if the error is found in a code block or module, it will
return the line number of the statement relative to the code block or
module.
The function/module part tells what function or module owns the
statement.
If the code block does not have an identifier or the statement is
declared outside code blocks, it will default to <module>.
The exception tells you what kind of error happened.
Some of them are built-in classes (e.g., ZeroDivisionError,
TypeError, and etcetera) while some are just errors (e.g.,
SyntaxError).
You can use them on your except blocks.
The exception description gives you more details with regards to
how the error occurred.
The description format may vary from error to error.
Using Exceptions to Prevent Crashes
Anyway, to know the exceptions that you can use, all you need to do is to
generate the error.
For example, using the TypeError found in the previous example, you can
capture that error too and provide the correct statements in response.
>>> def div(dividend, divisor):
try:
print(dividend / divisor)
except ZeroDivisionError:
print("Cannot Divide by Zero.")
except TypeError:
print("Cannot Divide by Anything Other Than a Number.")
except:
print("An unknown error has been detected.")
>>> div(5, 0)
Cannot Divide by Zero.
>>> div(5, "a")
Cannot Divide by Anything Other Than a Number.
>>> div(undeclaredVariable / 20)
An unknown error has been detected.
>>> _
However, catching errors this way can still be problematic.
It allows you to prevent a crash or stop, but you have no idea about what
happened.
To know the unknown error, you can use the as keyword to pass the
Exception details to a variable.
Convention wise, the variable detail is often used for this purpose.
For example:
>>> def div(dividend, divisor):
try:
print(dividend / divisor)
except Exception as detail:
print("An error has been detected.")
print(detail)
print("Continuing with the program.")
>>> div(5, 0)
An error has been detected.
division by zero
Continuing with the program.
>>> div(5, "a")
An error has been detected.
unsupported operand type(s) for /: 'int' and 'str'
Continuing with the program.
>>> _
The Else Block
There are times that an error happens in the middle of your code block.
You can catch that error with try and except.
However, you might not want to execute any statement in that code block if
an error happens.
For example:
>>> def div(dividend, divisor):
try:
quotient = dividend / divisor
except Exception as detail:
print("An error has been detected.")
print(detail)
print("Continuing with the program.")
print(str(dividend) + " divided by " + str(divisor) + " is:")
print(quotient)
>>> div(4, 2)
4 divided by 2 is:
2.0
>>> div(5, 0)
An error has been detected.
division by zero
Continuing with the program.
5 divided by 0 is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in div
Print(quotient)
UnboundLocalError: local variable 'quotient' referenced before assignment
>>> _
As you can see, the next statements after the initial fault are dependent on it
thus, they are also affected.
In this example, the variable quotient returned an error when used after the
try and except block since its supposed value was not assigned because the
expression assigned to it was impossible to evaluate.
In this case, you would want to drop the remaining statements that are
dependent on the contents of the try clause.
To do that, you must use the else block.
For example:
>>> def div(dividend, divisor):
try:
quotient = dividend / divisor
except Exception as detail:
print("An error has been detected.")
print(detail)
print("Continuing with the program.")
else:
print(str(dividend) + " divided by " + str(divisor) + " is:")
print(quotient)
>>> div(4, 2)
4 divided by 2 is:
2
>>> div(5, 0)
An error has been detected.
division by zero
Continuing with the program.
>>> _
The first attempt on using the function with proper arguments went well.
On the second attempt, the program did not execute the last two statements
under the else block because it returned an error.
The else block always follows except blocks.
The else block's function is to let Python execute the statements under it
when the try block did not return and let Python ignore them if an exception
happens.
Failing Silently
Failing silently or silent fails is a programming term often used during error
and exception handling.
From a user’s perspective, silent failure is a state wherein a program fails at a
certain point but never informs a user.
From a programmer’s perspective, silent failure is a state wherein the parser,
runtime development environment, or compiler fails to produce an error or
exception and proceed with the program.
This often leads to unintended results.
A programmer can also induce silent failures when he either ignores
exceptions or bypasses them.
Alternatively, he blatantly hides them and creates workarounds to make the
program operate as expected, even if an error happened.
He might do that because of multiple reasons, such as the error is not
program breaking or the user does not need to know about the error.
Handling the File Not Found Exception Error
There will be times when you will encounter the FileNotFoundError.
Handling such an error depends on your intent or purpose with regards to
opening the file.
Here are common reasons you will encounter this error:
You did not pass the directory and filename as a string.
You misspelled the directory and filename.
You did not specify the directory.
You did not include the correct file extension.
The file does not exist.
The first method to handle the FileNotFoundError exception is to make sure
that all the common reasons do not cause it.
Once you do, then you will need to choose the best way to handle the error,
which is completely dependent on the reason you are opening a file in the
first place.
Checking If File Exists
Again, there are always two ways to handle an exception: preventive and
reactive.
The preventive method is to check if the file exists in the first place.
To do that, you will need to use the os (os.py) module that comes with your
Python installation.
Then, you can use its path module’s isfile() function.
The path module’s file name depends on the operating system (posixpath for
UNIX, ntpath for Windows, macpath for old MacOS).
For example:
>>> from os import path
>>> path.isfile("random.txt")
False
>>> path.isfile("sampleFile.txt")
True
>>> _
Try and Except
You can also do it the hard way by using try, except, and else blocks.
>>> def openFile(filename):
try:
x = open(filename, "r")
except FileNotFoundError:
print("The file '" + filename + "' does not exist."
except FileNotFound:
print("The file '" + filename + "' does exist."
>>> openFile("random.txt")
The file 'random.txt' does not exist.
>>> openFile("sampleFile.txt")
The file 'sampleFile.txt' does exist.
>>> _
Creating a New File
If the file does not exist, and your goal is to overwrite any existing file
anyway, then it will be best for you to use the "w" or "w+" access mode.
The access mode creates a new file for you if it does not exist.
For example:
>>> x = open("new.txt", "w")
>>> x.tell()
0
>>> _
If you are going to read and write, use "w+" access mode instead.
Chapter 6. Variable Scope and Lifetime in
Python Functions
Variables and parameters defined within a Python function have local scope
implying they are not visible from outside.
In Python, the variable lifetime is valid as long the function executes and is
the period throughout that a variable exists in memory.
Returning the function destroys the function variables.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
def function_my()
marks=15
print(“The value inside the function is:”, marks)
marks=37
function_my()
Print”The value outside the function is:”,marks)
Function Types
They are broadly grouped into user-defined and built-in functions.
The built-in functions are part of the Python interpreter while the user
specifies the user-defined functions.
Exercise:
Give three examples of built-in functions in Pythons.
Function Argument
Calling a function requires passing the correct number of parameters;
otherwise, the interpreter will generate an error.
Illustration
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
def salute(name,message):
"""This function welcomes to
the student with the provided message"""
print("Welcome",salute + ', ' + message)
welcome("Brenda","Lovely Day!")
Note: the function welcome() has two parameters.
We will not get any error as it has been fed with two arguments.
Let us try calling the function with one argument and see what happens:
welcome(“Brenda”) #only one argument passed
Running this program will generate an error saying “TypeError: welcome()
missing 1 required positional argument.
The same will happen when we pass no arguments to the function.
Example 2:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
welcome()
The interpreter will generate an error “typeerror: welcome() missing 2
required positional arguments”.
Keywords Arguments in Python
Python provides a way of calling functions using keyword arguments.
When calling functions using keyword arguments, the order of arguments can
be changed.
The values of a function are matched to the argument position-wise.
Note:
In the previous example, function welcome when invoked as
welcome(“Brenda,” “Lovely Day!”).
The value “Brenda” is assigned to the argument name and “Lovely Day!” to
msg.
Calling the function using keywords
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
welcome(name=”Brenda”, msg=”Lovely Day!”)
Keywords not following the order
Welcome(msg=”Lovely Day!”, name=”Brenda”)
Arbitrary Arguments
It may happen that we do not have knowledge of all arguments needed to be
passed into a function.
Analogy: assume that you are writing a program to welcome all new students
this semester.
In this case, you do not how many will report.
Example
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
def welcome(*names):
“””This welcome function salutes all students in the names tuple.”””
for name in names:
print(“Welcome”.name)
welcome("Lucy","Richard","Fridah","James")
The output of the program will be:
Welcome Lucy
Welcome Richard
Welcome Fridah
Welcome James
Recursion in Python
The definition of something in terms of itself is called recursion.
A recursive function calls other functions.
Example:
Python program to compute integer factorials
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
Exercise
Write a Python program to find the factorial of 7.
Python Anonymous Function
Some functions may be specified devoid of a name, and these are called
anonymous functions.
The lambda keyword is used to denote an anonymous function.
Anonymous functions are also referred to as lambda functions in Python.
Syntax
lambda arguments: expression.
Lambda functions must always have one expression but can have several
arguments.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
double = lambda y: y * 2
# Output: 10
print(double(5))
Example 2:
We can use inbuilt functions such as filter () and lambda to show only even
numbers in a list/tuple.
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
first_marks = [3, 7, 14, 16, 18, 21, 13, 32]
fresh_marks = list(filter(lambda n: (n%2 == 0) , first_marks))
# Output: [14, 16, 18, 32]
print(fresh_marks)
Lambda function and map() can be used to double individual list items.
Example 3:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
first_score = [3, 7, 14, 16, 18, 21, 13, 32]
fresh_score = list(map(lambda m: m * 2 , first_score))
# Output: [6, 14, 28, 32, 36, 42, 26, 64]
Print(fresh_score)
Python’s Global, Local and Nonlocal
Python’s Global Variables
Variables declared outside of a function in Python are known as global
variables.
They are declared in the global scope.
A global variable can be accessed outside or inside of the function.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
y= "global"
def foo():
print("y inside the function :", y)
foo()
print("y outside the function:", y)
Explanation:
In the illustration above, y is a global variable and is defined as a foo() to
print the global variable y.
When we call the foo() it will print the value of y.
Local Variables:
A local variable is declared within the body of the function or in the local
scope.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
def foo():
x = "local"
foo()
print(x)
Explanation:
Running this program will generate an error indicating ‘x’ is undefined.
The error is occurring because we are trying to access local variable x in a
global scope, whereas foo() functions only in the local scope.
Creating a Local Variable in Python
Example:
A local variable is created by declaring a variable within the function.
def foo():
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
x = "local"
print(x)
foo()
Explanation:
When we execute the code, the output will be:
Local
Python’s Global and Local Variable
Using both local and global variables in the same code.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
y = "global"
def foo():
global y
x = "local"
y=y*2
print(y)
print(x)
foo()
Explanation:
The output of the program will be:
global global
local
Explanation:
We declared y as a global variable and x as a local variable in the foo().
The * operator issued to modify the global variable y, and finally, we printed
both y and x.
Local and Global Variables with the same name
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
y=6
def foo():
y=11
print(“Local variable y-“, y)
foo()
Print("Global variable y-", y)
Python’s Nonlocal Variables
A Python’s nonlocal variable is used in a nested function whose local scope
is unspecified.
It is neither global nor local scope.
Example:
Creating a nonlocal variable.
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
def outer():
y = "local variable"
def inner():
nonlocal y
y = "nonlocal variable"
print("inner:", y)
inner()
print("outer scope:", y)
Outer()
Global Keyword in Python
There are rules when creating a global keyword:
A global keyword is local by default when we create a variable within a
function.
It is global by default when we define a variable outside of a function, and
you do not need to use the global keyword.
The global keyword is used to read and write a global variable within a
function.
The use of a global keyword outside a function will have no effect.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
number = 3 #A global variable
def add():
print(number)
add()
The output of this program will be 3.
Modifying a global variable from inside the function.
number=3 #a global variable
def add():
number= number + 4 # add 4 to 3
print(number)
add()
Explanation:
When the program is executed it will generate an error indicating that the
local variable number is referenced before assignment.
The reason for encountering the error is that we can only access the global
variable but cannot modify it from inside the function.
Using a global keyword would solve this.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
Modifying global variable within a function using the global keyword.
number = 3 # a global variable
def add():
global number
number= number + 1 # increment by 1
print("Inside the function add():", number)
add()
print("In main area:", number)
Explanation:
When the program is run, the output will be:
Inside the function add(): 4
In the main area: 4
We defined a number as a global keyword within the function add().
The variable was then incremented by 1, variable number.
Then we called the add () function to print global variable c.
Creating Global Variables across Python Modules
We can create a single module config.py that will contain all global variables
and share the information across several modules within the same program.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
Create config.py
x=0
y=”empty”
Then create an update.py file to modify global variables
Import config
config.x=11
config.y=”Today”
Then create a main.py file to evaluate the changes in value
import config
import update
print(config.x)
print(config.y)
Explanation
Running the main.py file will generate:
11
Today
Python Modules
Modules consist of definitions as well as program statements.
An illustration is a file name config.py, which is considered as a module.
The module name would be config.
Modules are used to help break large programs into smaller, manageable, and
organized files, as well as promoting the reusability of code.
Example: Creating the First module
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
Def add(x, y):
“””This is a program to add two
numbers and return the outcome"""
outcome=x+y
return outcome
Module Import
The keyword import is used to import.
Example:
Import first
The dot operator can help us access a function as long as we know the
module's name.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
first.add(6,8)
Explanation:
Import Statement in Python
The import statement can be used to access the definitions within a module
via the dot operator.
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
import math
print("The PI value is", math.pi)
Import with renaming
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
import math as h
print(“The PI value is-“,h.pi)
Explanation:
In this case, h is our renamed math module with a view helping save typing
time in some instances.
When we rename, the new name becomes valid and recognized one and not
the original one.
From…import statement Python.
It is possible to import particular names from a module rather than importing
the entire module.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
from math import pi
Print("The PI value is-", pi)
Importing All Names
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
from math import*
print("The PI value is-", pi)
Explanation:
In this context, we are importing all definitions from a particular module, but
it is an encouraging norm as it can lead to unseen duplicates.
Module Search Path in Python
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
import sys
sys.path
Python searches everywhere, including the sys file.
Reloading a Module
Python will only import a module once, increasing efficiency in execution.
print(“This program was executed”)
import mine
Reloading Code
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
import mine
import mine
import mine
Mine.reload(mine)
Dir() built-in Python function
For discovering names contained in a module, we use the dir() inbuilt
function.
Syntax
Dir(module_name)
Python Package
Files in python hold modules and directories are stored in packages.
A single package in Python holds similar modules.
Therefore, different modules should be placed in different Python
packages.
Data types in Python
Numbers
The presence or absence of a decimal point separates integers and floating
points.
For instance, 4 is an integer, while 4.0 is a floating-point number.
On the other hand, complex numbers in Python are denoted as r+tj, where j
represents the real part, and t is the virtual part.
In this context, the function type() is used to determine the variable class.
The Python function instance() is invoked to make a determination of which
specific class function originates from.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
number=6
print(type(number))#should output class int
print(type(6.0))#should output class float
complex_num=7+5j
print(complex_num+5)
print(isinstance(complex_num, complex))#should output True
Important: Integers in Python can be of infinite length.
Floating numbers in Python are assumed precise up to fifteen decimal
places.
Number Conversion
This segment assumes you have prior basic knowledge of how to manually or
using a calculator to convert decimal into binary, octal, and hexadecimal.
Check out the Windows Calculator in Windows 10, Calculator version
Version 10.1804.911.1000, and choose programmer mode to convert
automatically.
Programmers often need to convert decimal numbers into octal, hexadecimal,
and binary forms.
A prefix in Python allows the denotation of these numbers to their
corresponding type.
Number SystemPrefix
Octal‘0O’ or '0o'
Binary‘0B' or '0b'
Hexadecimal'0X or '0x'
Example:
print(0b1010101)#Output:85
print(0x7B+0b0101)#Output: 128 (123+5)
print(0o710)#Output:710
Exercise:
Write a Python program to display the following:
a.0011 11112
b.7478
C.9316
Type Conversion
Sometimes referred to as coercion, type conversion allows us to change one
type of number into another.
The preloaded functions such as float(), int() and complex() enable implicit
and explicit type conversions.
The same functions can be used to change from strings.
Example
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
int(5.3)#Gives 5
int(5.9)#Gives 5
The int() will produce a truncation effect when applied to floating numbers.
It will simply drop the decimal point part without rounding off.
For the float() let us take a look:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
float(6)#Gives 6.0
ccomplex(‘4+2j’)#Gives (4+2j)
Exercise:
Apply the int() conversion to the following:
a.4.1
b.4.7
c.13.3
d.13.9
Apply the float() conversion to the following:
e.7
f.16
G.19
Decimal in Python
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
(1.2+2.1)==3.3 #Will return False, why?
Explanation:
The computer works with finite numbers, and fractions cannot be stored in
their raw form as they will create an infinitely long binary sequence.
Fractions in Python
The fractions module in Python allows operations on fractional numbers.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
import fractions
print(fractions.my_fraction(2.5))#Output 5/2
print(fractions.my_fraction(4))#Output 5
print(fractions.my_fraction(2,5))#output 2/5
Important:
Creating my_fraction from float can lead to unusual results due to the
misleading representation of binary floating point.
Mathematics in Python
To carry out mathematical functions, Python offers modules like random and
math.
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
import math
print(math.pi)#output:3.14159….
print(math.cos(math.pi))#the output will be -1.0
print(math.exp(10))#the output will be 22026.4….
print(math.log10(100))#the output will be 2
print(math.factorial(5))#the output will be 120
Exercise:
Write a python program that uses math functions from the math module to
perform the following:
a.Square of 34
b.Log1010000
c.Cos 45 x sin 90
D.Exponent of 20
Random Function in Python
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
import math
print(random.shuffle_num(11, 21))
y=[‘f’,’g’,’h’,’m’]
print(random.pick(y))
random.anypic(y)
print(y)
Print(your_pick.random())
Lists in Python
We create a list in Python by placing items called elements inside square
brackets separated by commas.
The items in a list can be of mixed data types.
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
list_mine=[]#empty list
list_mine=[2,5,8]#list of integers
list_mine=[5,”Happy”, 5.2]#list having mixed data types
Exercise:
Write a program that captures the following in a list: “Best”, 26,89,3.9
Nested Lists
A nested list is a list as an item in another list.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
list_mine=[“carrot”, [9, 3, 6], [‘g’]]
Exercise
Write a nested for the following elements: [36,2,1],”Writer”,’t’,[3.0, 2.5]
Accessing Elements from a List
In programming and in Python specifically, the first time is always indexed
zero.
For a list of five items, we will access them from index0 to index4.
Failure to access the items in a list in this manner will create an index error.
The index is always an integer as using other number types will create a type
error.
For nested lists, they are accessed via nested indexing.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
list_mine=[‘b’,’e’,’s’,’t’]
print(list_mine[0])#the output will be b
print(list_mine[2])#the output will be s
print(list_mine[3])#the output will be t
Exercise:
Given the following list:
your_collection=[‘t’,’k’,’v’,’w’,’z’,’n’,’f’]
a.Write a Python program to display the second item in the list
b.Write a Python program to display the sixth item in the last
C.Write a Python program to display the last item in the list.
Chapter 7. Modules
For example:
>>> file1 = open("sampleFile.txt")
>>> file1.tell()
0
>>> file1.read()
'Hello World'
>>> file1.tell()
11
>>> file1.read()
''
>>> _
To move the file pointer to a position you desire, you can use the seek()
function.
For example:
>>> file1 = open("sampleFile.txt")
>>> file1.tell()
0
>>> file1.read()
'Hello World'
>>> file1.tell()
11
>>> file1.seek(0)
0
>>> file1.read()
'Hello World'
>>> file1.seek(1)
1
>>> file1.read()
'ello World'
>>> _
The seek() method has two parameters.
The first is offset, which sets the pointer’s position depending on the second
parameter.
Also, the argument for this parameter is required.
The second parameter is optional.
It is for whence, which dictates where the “seek” will start.
It is set to 0 by default.
If set to 0, Python will set the pointer’s position to the offset
argument.
If set to 1, Python will set the pointer’s position relative or in
addition to the current position of the pointer.
If set to 2, Python will set the pointer’s position relative or in
addition to the file’s end.
Note that the last two options require the access mode to have binary access.
If the access mode does not have binary access, the last two options will be
useful to determine the current position of the pointer [seek(0, 1)] and the
position at the end of the file [seek(0, 2)].
For example:
>>> file1 = open("sampleFile.txt")
>>> file1.tell()
0
>>> file1.seek(1)
1
>>> file1.seek(0, 1)
0
>>> file1.seek(0, 2)
11
>>> _
File Access Modes
To write to a file, you will need to know more about file access modes in
Python.
There are three types of file operations: reading, writing and appending.
Reading allows you to access and copy any part of the file’s content.
Writing allows you to overwrite a file’s contents and create a new one.
Appending allows you to write on the file while keeping the other content
intact.
There are two types of file access modes: string and binary.
String access allows you to access a file’s content as if you are opening a text
file.
Binary access allows you to access a file in its rawest form: binary.
In your sample file, accessing it using string access allows you to read the
line “Hello World.”
Accessing the file using binary access will let you read “Hello World” in
binary, which will be b'Hello World'.
For example:
>>> x = open("sampleFile.txt", "rb")
>>> x.read()
b'Hello World'
>>> _
String access is useful for editing text files.
Binary access is useful for anything else, like pictures, compressed files, and
executables. In this book, you will only be taught how to handle text files.
You can enter multiple values in the file access mode parameter of the open()
function.
But you do not need to memorize the combination.
You just need to know the letter combinations.
Each letter and symbol stands for an access mode and operation.
For example:
r = read-only—file pointer placed at the beginning
r+ = read and write
a = append—file pointer placed at the end
a+ = read and append
w = overwrite/create—file pointer set to 0 since you create the file
w+ = read and overwrite/create
b = binary
By default, file access mode is set to string.
You need to add b to allow binary access.
For example: "rb"
Writing to a File
When writing to a file, you must always remember that Python overwrites
and does not insert file.
For example:
>>> x = open("sampleFile.txt", "r+")
>>> x.read()
'Hello World'
>>> x.tell(0)
0
>>> x.write("text")
4
>>> x.tell()
4
>>> x.read()
'o World'
>>> x.seek(0)
0
>>> x.read()
'texto World'
>>> _
You might have expected that the resulting text will be “textHello World.”
The write method of the file object replaces each character one by one,
starting from the pointer's current position.
Practice Exercise
For practice, you need to perform the following tasks:
Create a new file named test.txt.
Write the entire practice exercise instructions on the file.
Close the file and reopen it.
Read the file and set the cursor back to 0.
Close the file and open it using append access mode.
Add a rewritten version of these instructions at the end of the file.
Create a new file and put similar content to it by copying the
contents of the test.txt file.
Summary
Working with files in Python is easy to understand but difficult to implement.
As you already saw, there are only a few things that you need to remember.
The hard part is when you are actually accessing the file.
Remember that the key things you should master are the access modes and
the file pointer's management.
It is easy to get lost in a file that contains a thousand characters.
Aside from being versed with file operations, you should also supplement
your learning with the functions and methods of the str class in Python.
Most of the time, you will be dealing with strings if you need to work on a
file.
Do not worry about binary yet.
That is a different beast altogether, and you will only need to tame it when
you are already adept at Python.
As a beginner, expect that you will not deal yet with binary files that often
contain media information.
Anyway, the next lesson is an elaboration on the “try” and “except”
statements.
You’ll discover how to manage and handle errors and exceptions effectively.
Chapter 9. Object-Oriented Programming
If you ask for these attributes from the second object, the output will be what
you sent with it.
Here’s an example:
print(SUV.model)
print(SUV.license)
Now, if you want to access the methods, simply use the dot operator again
and ask for the methods.
Here’s how:
print(fordMustang.honk())
And it outputs:
Firstly, we write our child class and use the parenthesis to provide to it, the
parent class (Car).
Next, we declare the __init__ function just like we did before and pass to it
the parameters and the self keyword to refer to the object.
Next, something strange.
We use the super() function and use the method __init__ to refer to the
parent class's init method.
This is done so a connection can be made between the parent class and
the child class, and now, it can access all attributes and methods of the
parent class.
Although it doesn’t have any function of its own right now, it can definitely
be added in later.
Next, we make an object of our new ElectricCar class and ask for the
methods and attributes, which yield expected output since now a relationship
is made between the parent and child or super and subclass.
If you decide to assign methods to the child class, remember, the parent class
can’t access them.
But, the child class can definitely (always) access the methods of the parent
class.
Importing Classes
As your programs grow, so will the complexity, both in logic and file size.
It is always recommended to ship your classes as individual files and import
them wherever they are required.
This is possible using the import statements we studied a while ago.
Here’s how you can import the classes into another file and use them
properly:
1. from car import Car
2. from car import ElectricCar
3. from car import Car, ElectricCar
4. from car import *
5. import car
Chapter 10. Real-World Examples of Python
One might argue that Python's era was just 2017 when it witnessed some
great rise in popularity and growth across the world. However, according to
statistics and data, the recent rise in Python's growth could not be ignored.
However, why do you think it will keep on attaining the rise in expansion and
in size?
To answer the question, we dive into the market data and the scale of Python
adoption and acquisition by corporations and companies around the world.
SO the reason behind the popularity of Python is one and simple.
It will be as popular and widely used five years from now as it was five years
ago.
This is a big statement, and to prove this, we need to see in detail what makes
Python so special for these developers and programmers.
Years ago, when Python came into the market, people believed it would be
dead within months of inception. In face when Larry Wall, who is also the
founder and brain behind programing language Perl, was delivering his third
annual state of Pearl Opinion, he said that there are some programming
languages out there in the market that are C++, Java, Perl, Visual Basics,
Javascript and in the last Python.
Back then, the leading language for programming was C++, and Perl was the
third number in the market.
Python had very low demand and was not included among the PLs that could
grow.
However, in the years to follow, Python grew with tremendous speed and
outshined Perl as well.
According to Stack Overflow, the visitor volume to question and enquire
about Python increased more rapidly than Perl.
The following are the reasons behind the rise and super demand for Python
among developers.
Data Science
This is one of the most adored languages among data scientists, unlike R and
C++.
So the current era is the era of big data, and since Python supports large sets
of libraries, the internet, and prototypes, Python is the best and fully suited
language for the operations.
PyMySQL, PyBrain, and NumPy are the reason why Python is so extensively
demanded.
In addition, integrations and programming are the things a programmer has to
deal with in everyday life, and this is the reason behind the huge demand for
Python as well because it provides easy integration even of existing apps or
sites to other programming languages.
This makes it future-oriented and scalable.
Machine Learning
These days, in the industry, artificial intelligence, and machine learning have
created a huge buzz with every industry investing in the areas to maximize
their revenue and cut costs.
This is not really possible without the induction of Python.
It is actually an interpreted language, and its use makes it elucidated enough
to be interpreted by machines and to be understood by the hardware.
The growth of ML has been on the rise in the last few years, and I think this
is also one of the reasons why Python has witnessed a surge in its demand.
Applications in Web Development
According to data, Python is chosen by two out of three developers who, in
the start, worked with OHO, and this is an achievement.
In the last couple of years, the rising trend of Python shows that it seems like
the best alternative. It offers Flask and Django, which makes the process of
web development easy and quick. Due to these reasons and features, leading
tech giants like Google, Facebook, Instagram, etc., have been using it for a
long time. Uber and Google use it for their algorithms.
In addition, it is super simple, and this is the reason why it is easy to work
with and adaptable.
Automation
Software development applications are SCons, which is for build control,
Roundup, and Trace, which are for bug tracking and project management.
For IDE integrated development environments, a Roster is used.
• The most important stuff related to Python is that it provides special
applications for education.
• Its applications in business include Tryton, which is a 3-tier and
advanced level application platform.
Another management software called Odoocomes with a huge deal of
business applications. This actually makes Python an all-rounder.
• We have Twisted Python for network programming, which provides
a platform and framework for the network programming that is
asynchronous.
It has a simple socket interface.
• We all know that the gaming industry is evolving with great potential
and the ability to create a replicated amount of revenue.
Python's applications for gaming are very safe to use and have been
pretty much and widely used.
PyGame and PyKyra are bi-development frameworks for games.
There is also a variety of 3D rendering options in the libraries.
• Moreover, we have applications that interest the developers to a huge
extent and are used widely.
We have console-based applications, applications for robotics,
machine learning, web scraping and scripting, and whatnot.
These are the main reason why Python is the best fit in the industry from the
point of view of a developer.
According to a report of myTectra, the jobs posted in Naukri from 2014 to
2017 have been monitored.
The trend of Python jobs is compared to the world’s number one language
showing different results.
Things We Can Do in Python
In this chapter, we will discuss many things that you can do in Python.
Some of the things we can do in Python include the comments, reading and
writing, files and integers, strings, and variables.
After reading this book, we are sure that you will be able to create a program
that will run effectively.
Due to the interactive and descriptive nature of Python, a beginner can handle
many things using it.
Therefore, this chapter will discuss some aspects and comments in Python to
help you get started.
You can make amazing codes in a short time using the Python programming
language.
Comment
A comment in the Python programming starts with the # sign.
This continues until the programmer gets to the end of the line.
A good example is;
# This is a comment
Print (hello, thanks for contacting us)
It instructs your computer to print “Hello, thanks for contacting us.”
The Python interpreter ignores all the comments.
As a programmer, however, you should not leave a comment after every line.
You can put in a comment when you need to explain something.
Since Python does not support long comments, it is important to use short
and descriptive comments to avoid them going across the lines.
Reading and Writing
You will realize that some program requests specific information or show the
text on the screen.
Sometimes we start the program code by informing the readers about our
programs.
To ease things for the other coders, it is important to give it a name or title
that is simple and descriptive.
As a programmer, you can use a string literal that comprises the print
function to get the right data.
String literal is a line of the text surrounded by the quotes.
They can be either double or single quotes.
Although the type of quotes a programmer use matters less, the programmer
must end with the quotes that he/she has used at the beginning of the phrase.
You can command your computer to display a phrase or a word on the screen
by just doing as discussed above.
Files
Apart from using the print function to obtain a string when printing on the
screen, it can be used to write something onto the file.
First, you will have to open up the myfile.txt and write on it before assigning
it the myfile, which is a variable.
Once you have completed the first step, you will have to assign “w” in the
new line to tell the program that you will only write or make changes after
the file has opened.
It is not mandatory to use the print function; use the right methods like the
reading method.
The reading method is used to open specific files to help you read the
available data. You can use this option to open a specific file.
Generally, the read method helps the programmers to read the contents into
variable data, making it easy for them to open the program they would like to
read.
Integers
Always make sure that the integers are kept as whole numbers if you are
using them. They can be negative or positive only if there are no decimals.
However, if your number has a decimal point, use it as a floating number.
Python will automatically display such integers on the screen.
Moreover, you cannot place one number next to others if you are using the
integers because Python is a strongly typed language; thus, it will not
recognize them when you use them together.
However, you put both the number and the string together by making sure
you turn the number into a string first before going to the next steps.
Triple Quotes
After reading and understanding both the single and double quotes, it is now
time to look at the triple quotes.
The triple quotes are used to define the literal that spans many lines.
You can use three singles, double, or single when defining an authentic.
Strings
Although a string is seen as a complicated thing to many beginners, it is a
term used by the programmers when referring to a sequence of characters and
works just like a list.
A string contains more functionality, which is specific than a list.
You will find it challenging to format the strings when writing out the code
because some messages will not be fixed easily due to its functionality.
String formatting is the only way to go away within such a situation.
Escape Sequences
They are used to donate special characters that are hard to type on the
keyboard or those that can be reserved to avoid confusion that may occur in
programming.
Operator Precedence
It will help you to track what you are doing in Python.
It makes things easy when ordering the operation to receive the right
information.
So, take enough time to understand how the operator precedence works to
avoid confusion.
Variables
Variables refer to the labels donated somewhere in the computer memory to
store something like holding values and numbers.
In the programming typed statistically, the variables have predetermined
values.
However, Python enables you to use one variable to store many different
types.
For example, in the calculator, variables are like memory function to hold
values that can be retrieved if you need them later.
The variables can only be erased if you store them in the newer value.
You will have to name the variable and ensure it has an integer value.
Moreover, the programmer can define a variable in Python by providing the
label value.
For instance, a programmer can name a variable count and even make it an
integer of one, and this can be written as; count=1.
It allows you to assign the same name to the variable, and in fact, the Python
interpreter cannot read through the information if you are trying to access
values in the undefined variable.
It will display a message showing syntax error.
Also, Python provides you with the opportunity of defining different
variables in one line, even though this not good according to our experience.
The Scope of a Variable
It is not easy to access everything in Python, and there will be differences in
the length of the variables.
However, the way we define the variable plays a vital role in determining the
location and the duration of accessing the variables.
The part of the program that allows you to access the variable is called the
Scope, while the time taken for accessing the variable is a lifetime.
Global variables refer to the variables defined in the primary file body.
These variables are visible throughout the file and also in the file that imports
specific data.
As such, these variables cause a long-term impact, which you may notice
when working on your program.
This is the reason why it is not good to use global variables in the Python
program.
We advise programmers to add stuff into the global namespace only if they
plan to use them internationally.
A local variable is a variable defined within another variable.
You can access local variables from the region they are assigned.
Also, the variables are available in the specific parts of the program.
Modifying Values
It is easy for an individual to define a particular variable whose values have
been set for many programming languages. The values, which cannot be
modified or changed in the programming language, are called constants.
Although this kind of restriction is not allowed in Python, there are used to
ensure some variables are marked, indicating that no one should change those
values.
You must write the name in capital letters, separated with underscores.
A good example is shown below:
NUMBER_OF_HOURS_IN_A_DAY=24
It is not mandatory to put the correct number in the end.
Since Python programming does not keep tracking and has no rules for
inserting the correct value in the end, you are free and allowed to say, for
example, that they are 25 hours in a day.
However, it is important to put the correct value for other coders to use in
case they want.
Modifying values is essential in your string as it allows a programmer to
change the maximum number in the future.
Therefore, understanding the working of the string in the program contributes
a lot to your program's success.
One has to learn and know where to store the values, the rules governing each
value, and how to make them perform well in a specific area.
The Assignment Operator
It refers to an equal sign (=).
You will be using the assignment operator to assign values to the variable
located at the left side on the statement's right.
However, you must evaluate if the value on the right side is an arithmetic
expression.
Note that the assignment operator is not a mathematical sign in the
programming because, in programming, we are allowed to add all types of
things and make them look like they are equivalent to a certain number.
This sign is used to show that those items can be changed or turned into the
part on the other side.
Chapter 11. Getting Started; Python Tips and
Tricks
We have spent the last few days of this guidebook looking at some of the
different parts of the Python language that we can work with.
These are meant to help us get going with some of our coding in Python and
will ensure that we can write some of your codes in no time.
With some of this information in mind, we can work on some of the final
skills that we need to focus on before we are done.
We are going to look at some of the tips and tricks that will help you to get
started with Python, along with how we can work with web scraping and
debugging some of our programs as well.
Let’s get started with this one to help us get started and finalize how good our
codes can be.
Web Scraping
Imagine for a moment that we are going to pull up a large amount of data
from many websites, and we want to be able to do this at a very fast rate.
How would we be able to go through this without having to go manually
through each of the websites that we have and gathering the data in this
manner?
This is where the process of web scraping is going to come into play.
Companies will use web scraping to collect a large amount of information
from websites.
But why does someone want to go through and collect all of this data, in such
large amounts, from these websites in the first place?
There are a lot of reasons for this, and some of them are going to include the
following:
Price comparison: some of the different services that are out there,
such as ParseHub, will work with this process in order to collect
data from websites for online shopping and then can use this in
order to compare prices of similar products.
Email address gathering: we can use the process of web scraping in
order to help with marketing.
This can help us to collect the email IDs that come with customers
and then send out bulk emails to these individuals as well.
Social media scraping: web scraping is going to be used to collect
data from social media sites and then figure out what is trending.
Research and development: web scraping is going to be used to
help a company collect a lot of data from websites.
We can then analyze this and use it to finish our surveys and to help
out with research and development.
Job listing: details regarding openings of jobs, interviews, and more
can be collected from a variety of websites, and then we can list
them in one place in order to make them easier for the user to
access
Web scraping is going to be more of an automated method that we can use in
order to get a huge amount of data from any website that we choose.
The data that we are able to get out of these websites will be unstructured.
And this web scraping helps a company to collect all of this data and then
will ensure that they are able to store it in a structured form.
There are a variety of methods that we are able to use in order to scrape these
websites that we want, including online Services, writing out some of your
own codes, and APIs.
Talking about whether or not scraping of this kind is seen as legal or not, it
can depend on what the website says.
Some websites are fine with this, and some are not.
You can check with each website to figure out whether they are fine with it,
and if they are, you are able to continue with your web scraping tools and
gather up the information that you need.
Since we are talking about Python here, we are going to take some time to
see how we are able to use Python to help out with web scraping.
But this brings up the reasons why we would want to work with Python to
help out with this process rather than working with some of the other coding
languages that are out there. Some of the features that come with Python and
can make it more suitable for web scraping will include:
It is easy to use: the code that you are able to use along with Python
is going to be simple.
This ensures that any of the codes that you want to use for web
scraping will not be as messy to work with and can be easy to use.
A large library collection: There are a lot of libraries that work with
data science and web scraping that are also compatible with what
the Python language is able to do.
These include options like Pandas, Matplotlib, and NumPy.
This is why you will find that the Python language is going to be
suitable for web scraping and even for some of the other
manipulations that you want to do with the extracted data.
Dynamically typed: this is something in Python where you will not
need to go through and define all of the types of data that you are
using with our variables.
Instead, you are able just to use these variables wherever you would
like.
This is going to save a lot of time when it comes to working on the
codes and can make your job faster than ever.
The syntax of Python is going to be easy to understand the syntax
that we are able to see with Python is easy to understand, mainly
because the statements that come with this are going to be written in
English.
It is going to be expressive and easy to read, and the indentations
will make it easier for us to figure out between the different parts of
the code.
A small line of code is able to handle some large tasks.
Web scraping is a process that we are going to use in order to save
some time.
And with Python, you can write out a small amount of code to get
some of the big tasks that you would like to accomplish.
This is going to save you time not only when it comes to figuring
out the important data that comes in that website, but can also help
you to save time when you would like to write out the codes.
Community: at times, when you are a beginner, you are going to
find that there are parts of the code that are hard to work with and
are not going to go as smoothly as you had hoped in the process.
This is where you will find the Python language to be healthy.
If you get stuck while writing out some of your code, you will like
that the Python community is going to help you to answer your
questions and get things done on the code in no time.
Now that we know some of the benefits that come with Python, especially the
ones that are going to help us to handle some of the web scrapings that we
want to do, it is time for us to take things to the next step and look at how the
process of web scraping is going to work.
When you run out the code that you want to work within web scraping, you
will find that there is a request that is sent out to the URL.
Then there is going to be a response sent back from that request, and then the
server is able to send the data and allows you a chance to read the page,
whether it is XML or HTML at the time.
The code is then able to go through and parse the XML or HTML page, find
the data, and takes it out.
The location where you are going to find this data when it is extracted will
depend on what you told the code to do.
Often it is going to be moved over to a database so that you are able to search
through it later and learn more from it as well.
There are going to be a few simple steps that you are able to take to make
something to help us go through the process of extracting the data with the
help of web scraping in Python.
The steps that will help you to use Python to help with web scraping will
include:
Find the URL that you would like to scrape in the first place.
Inspect the page that you are planning on using.
Find the data that is on the page that you would like to extract.
Write out the code that you would like to use with the help of
Python in order to complete this process.
Run the code that you just wrote and then extract out the data that
you would like to use.
Store the data in the format that would be the most helpful for you
in the process.
There are also a few options that you are able to use when it is time to work
on the process of web scraping.
As we know, Python is already able to be used for a lot of different types of
applications, and there are going to be a ton of libraries with Python that is
going to be used for different purposes.
There are a few libraries that work the best when it comes to working with
the process of data web scraping will include:
1. Selenium: this is going to be a web testing library.
It is going to be used to help automate some of the activities that are
found on your browser.
2. BeautifulSoup: this is going to be one of those packages that you
are able to use with Python to help us to parse HTML and XML
documents.
It is also able to create parse trees that can help us to extract the data
in an easy manner.
3. Pandas: this is one of the best libraries to rely on when it is time to
handle any kind of work that you would like in data analysis and
data science.
Pandas are often going to be used to help out with any of the data
analysis and the data manipulation that you would like.
When it comes to web scraping, you will find that Pandas is going
to be used in order to extract the data and then get it stored in the
right format in the way that you would like along the way.
There are many times when a company is going to try and gather up data
from other websites and from many other sources.
This is one of the first steps that is going to be found when we are working
with data analysis and using that information to improve a business through
their customers, the industry, or from the other competition out there.
But going through and manually gathering all of that data is going to take too
long and can be really hard to work with as well.
With the large amounts of data that are being used and generated on a daily
basis, it is no wonder that so many companies are working with processes
like web scraping to handle all of the work in a timely manner as well.
When we work with web scraping and do some of the codings that are
necessary with the help of Python, we will find that we are able to get
through the information in a fast manner and get it stored in the right place
for our needs, without having to do all of the work manually.
This can make the process of data analysis much easier overall and will
ensure that we are able to see some of the results that we want with this as
well.
And with some of the right Python algorithms and codes, we can get data
scraping done in no time.
Chapter 12. Common Programming
Challenges
The excitement about programming can fizzle out fast and turn into a
nightmare.
There are unexpected challenges that might make life difficult for you,
especially as a beginner programmer. However, these challenges should not
set you back or kill your resolve.
They are common challenges that a lot of people have experienced before,
and they overcame them, as you will too.
If you want to succeed in programming, you should be aware of the fact that
mistakes do happen, and you will probably make many of them.
The downside of mistakes is that you can feel you are not good enough.
Everyone else seems to be doing fine, but not you.
On the flip side, mistakes are an opportunity for you to learn and advance.
No one was born as good as they are today.
What we are is the sum of mistakes and learning from those mistakes and
experiences.
Feel free to reach out to mentors whenever you feel stuck.
Deadlines and bug reports might overwhelm you, but once you get the hang
of it, you will do great.
The following are some common challenges that you might experience as a
beginner programmer.
Debugging
You feel content with a project, satisfied that it will run without a hitch and
perform the desired duties.
However, when you arrive at your desk in the morning, your quality
assurance team has other ideas.
They point out what seems like endless issues with the project.
Perhaps the OK button is not responsive; the error messages are not
displaying correctly, and so forth.
All these are issues that eventually leave a negative impact on the user
experience.
You must get back to the drawing board and figure out where the problem
lies.
Debugging will be part of your life as a programmer.
It is not enjoyable, but it is reality.
Debugging is one of the most exhausting things you have to do.
If you are lucky, you will encounter bugs that can be fixed easily.
Debugging costs you hours and lots of coffee.
However, you should not feel downtrodden yet.
Bugs are all over the place in programming.
Even the best code you will ever come across needs debugging at some
point.
Solution
How do you handle the debugging process and make your life easier?
The first step is to document your work.
Documentation might seem like a lot of work for you, but it helps you trace
your steps in the event of an error.
That way, you can easily trace the source and fix it, saving you from
inspecting hundreds or thousands of code.
Another way of doing light work of debugging is to recreate the problem.
You must understand what the problem is before you try to solve it.
If you recreate the problem, you isolate it from the rest of the code and get a
better perspective of it.
Talk to someone.
You might not always have all the answers.
Do not fear anyone, especially if you work in a team.
Beginner programmers often feel some people are out of reach, perhaps
because of the positions they hold.
However, if you do not ask for help, you will never really know whether the
person will be helpful or not.
The best person to ask for help, for example, is the quality tester who
identified the problem, especially if you are unable to recreate the problem.
Working Smart
As a programmer, one thing you must be aware of is that you will be sitting
down for hours on end working on some code.
This becomes your normal routine.
However, you are aware of the risks this poses to your health. Neck sprains,
numb legs, back pain, pain in your palms and fingers from typing away all
day.
For a beginner, you might not be ready for the challenge yet.
However, you must still dig in daily to meet your deliverables.
Solution
The first thing you must consider is regular exercise.
If you work a desk job, it is possible to lose motivation and feel exhausted
even before your workday is over.
You can tackle this by keeping a workout routine.
Jog before you go to work every morning, take a brisk half-hour walk, and so
forth.
There are many simple routines that you can initiate, which will help you
handle the situation better.
While at work, take some time off and walk around—without looking like
you are wasting time.
This helps to relieve your body of the pain and pressure, and more
importantly, allows for proper blood circulation.
Other than that, you do not have to keep typing while seated.
Stand up from time to time.
Some companies have invested in height-adjustable desks, which help with
this.
User Experience
One of the most common challenges you will experience as a programmer is
managing user experiences.
You will come across a lot of clients in the course of your programming
career.
However, not all clients know how to communicate their needs.
As a result, you will be involved in a lot of back and forth on project details
and deliverables.
Most users have a good idea of what they need the project you are developing
to do.
However, this is not always the same as what your development team
believes.
Given that most beginner programmers never interact directly with the
clients, it might be difficult for you to understand them, especially in a team
project.
Solution
The best way around this is to figure out the best features of the project.
Your client already knows what they want the project to do.
Ask the right questions, especially to your team members who are in direct
contact with the client or the end-user.
The best responses will often come from designers and user experience
experts.
Their insight comes from interacting with users most of the time.
Another option is to test the product you are designing.
You have probably used test versions of some products in the past.
Most major players in the tech industry release beta versions of their products
before the final.
This way, users try it out, share their views, ideas, and challenges they
encounter.
This information is collected and used to refine the beta product before the
final one is released.
Testing your product allows you to identify and fix bugs before you release
the product to the end-user.
It also allows you to interact with the user and gauge the level of acceptance
for your project.
Estimates
A lot of beginner programmers struggle with scheduling.
Perhaps you gave an estimate for a task and you are unable to meet it.
You are now a professional.
Never delude yourself that you are not, perhaps because you are a beginner.
This industry focuses on deadlines a lot.
In software development, estimates are crucial.
They are often used to plan bigger schedules for projects, and in some cases,
agree on the project quotes.
Delays end up in problems that might, in the long run, affect trust between
the parties involved.
Solution
The first step towards getting your estimates right is to apportion time
properly.
Time management is key.
Set out a schedule within which you can complete a given task.
Within that schedule, allow yourself ample buffer time for any
inconvenience, but not too much time.
For example, allow yourself 30-40 minutes for an assignment that should
take 20 minutes.
Another way of improving your scheduling challenges is to break down
assignments into micro milestones.
A series of small tasks is easier to manage.
Besides, when you complete these micro assignments, you are more psyched
about getting onto the next one, and so on.
You end up with a lighter workload, which is also a good way to prevent
burnout.
Constant Updates
The tech industry keeps expanding in leaps and bounds.
You can barely go a month before you learn about some groundbreaking
work.
Everything keeps upgrading or updating to better, more efficient versions.
Libraries, tools, and frameworks are not left behind, either.
Updates are awesome.
Most updates improve user experiences and bolster the platform security.
However, updates come with undue pressure, even for the most experienced
programmers out there.
Solution
Stay abreast of the latest developments in your field of expertise.
You cannot know everything, but catching up on trends from time to time
will help you learn some new tools and tips available, which can also help
you improve your skills and develop cutting edge products.
Another option is to learn.
The beauty of the world of IT is that things are always changing.
It is one of the most dynamic industries today.
Carve out half an hour daily to learn something new.
You will be intrigued by how much you will have mastered after a few
weeks.
In your spare time, challenge yourself to build something simple, solve a
problem, and so forth.
There are lots of challenge websites available today where you can have a go
at real-world problems.
Problems Communicating
Beginner programmers face communication challenges all the time.
You are new to the workplace, so you do not really know anyone.
Most of the team members and managers are alien to you, and as a result, you
often feel out of place. At some point in time, every programmer goes
through this.
You feel like a baby among giants.
Eventually, the pressure gets to you, and you make a grave mistake, which
could have been avoided if you reached out to someone to assist.
Solution
Dealing with communication problems is more than just a social interaction
concern.
First, you must learn to be proactive.
If something bugs you, ask for help.
The worst that can happen is people might laugh, especially if it is a rookie
question, but someone will go out of their way and help you.
If they don’t and something goes awry, the department shoulders the blame
for their ignorance.
Before you know it, people will keep checking in on you to make sure you
are getting it right, and you might also make some good friends in the
process.
Consistency is another way to handle the communication challenge.
For a beginner, you might not always get everything right.
These are moments you can learn from.
With practice, you grow bolder and learn to express yourself better over
time.
Security Concerns
Data is the new gold.
This is the reality of the world right now.
Data is precious and is one of the reasons why tech giants are facing lawsuits
all over the place.
Huawei recently found itself in a spat with the US government that ended up
in a host of severed ties.
There are so many reasons behind the US government's hard stance against
Huawei, and most of them circle back to data.
People are willing to pay a great deal of money to access specific data that
can benefit them in one way or the other.
Some companies play the short-term game; others are in it for the long-term.
Competitors also use nefarious ways to gain access to their competitors’
databases and see what they are working on and how they do it.
As a programmer, one thing your clients expect from you is that their data is
safe, and the data their clients share with them through your project.
Beginner programmers are fairly aware of all the security risks involved.
This should not worry you so much, especially if you are part of a team of
able developers.
They will always have contingency measures in place.
However, you must not be ignorant of security loopholes, especially in your
code.
Solution
Hackers are always trying to gain access to some code.
You cannot stop them from trying.
However, you can make it difficult for them to penetrate your code.
Give them a challenge.
The single biggest threat to any secure platform is human interaction.
At times, someone will not compromise your code from outside but someone
you know.
In most cases, they compromise your code without knowing they do–unless
they did it intentionally.
Make sure your workstation is safe.
Every time you step away from your workstation, ensure your screen is
locked, and if you are going away for a long time, shut down your devices.
It is also advisable in your programming language that you use parameterized
queries, especially for SQL injections.
This is important because most hackers use SQL injections to gain access and
steal information.
Relying on Foreign Code
You have written some code for a few years and believe in your ability.
You are confident you are good enough, hence being hired by the company.
However, make peace with the fact that you will have to work on projects
that were written by someone else.
Working with another person’s code is not always an easy thing, especially if
their code seems outdated.
There is a reason why the company insists on using that particular code.
The worst possible situation would be company politics–they occur
everywhere.
Someone wrote some code that the entire company relies on, but you cannot
change or question it because the original coder connects with the company
hierarchy.
Often this raises a problem where you are unable to figure out the code.
Solution
Since there is not much you can do about the code, why not try to learn it?
If you can, talk to the developer who wrote it and understand their reasoning
behind it.
This way, it is easier for you to embrace their style, and you will also have a
smooth time handling your projects.
You never know; you might just show them something new and help them
rethink their code.
Another option is to embrace this code.
It is not yours, but it is what you have and will be using for a very long time.
Change your attitude about that code.
Take responsibility for the code and work with it.
This way, your hesitation will slowly fade away.
Lack of Planning
While you have a burning desire to impress in your new place of work, you
must have a plan.
Many beginner programmers do not.
Many programmers jump into writing code before stopping in their tracks to
determine the direction they want to steer the code.
The problem with this approach is that you will fail to make sense.
The code might sound right in your head, but on paper, nothing works.
Solution
Conceptualize an idea.
Everything starts with an idea.
Say you want to write a program that allows users to share important calendar
dates and milestones with their loved ones.
Focusing on this idea helps you remember why you are writing that code.
Once you have an idea, how do you connect it with real problems?
What are the problems you are trying to solve?
How are they connected to your idea?
This also begs the question—why do people need your program?
Planning will help you save time when writing a program, and at the same
time, help you stay on track.
Finally
In programming, everyone starts somewhere.
Being the new person in the company should not scare you.
Communicate with your peers and seniors, be willing to learn from them, and
all the things that might seem overwhelming will somehow become easier as
time goes by.
Conclusion
Programming is not easy. In fact, it’s rather difficult, and there are topics that
are sadly too esoteric to cover in this book.
For example, we didn’t get to the bulk of file operations, nor did we get to
things like object-oriented programming.
But I hope what I’ve given you is a very solid foundational understanding of
Python so that you can get ready to learn about these things.
Python—It is a language named after Monty Python.
It is a programming language that has taken the world by storm.
The applications we have seen so far, the examples we have discovered, and
the future prospects of the language, when combined, point out one thing for
sure.
If you are a programmer, Python is your ticket to the future.
When learning a new language, there will always be challenges.
There will be times where you might even be frustrated and call it a day.
The thing to remember here is this: many others have gone through this road
just like you.
Some have gone on to become successful, while others have remained within
the shadow of someone else.
It is up to you to grab the opportunity and become a unique and different
programmer, and learning Python is just a part of the journey.
Through Python, you will be able to do so much more than just design 2D
snake games.
Python has paved the way for many success stories and has certainly become
the most popular language.
Now you know why!
It is time for you to add Python to your resume and deliver results in the most
effective and efficient manner possible.
Good luck, and have a great programming journey ahead!
I am not going to hold your hand.
But what I can say is that you have worked hard to be a programmer, and you
have worked hard throughout the course of this book, likewise.
Not all of the concepts within this book are easy to understand, even with
more in-depth explanations.
My goal here wasn’t explicitly to teach you Python or object-oriented
programming or any of that: my goal was to teach you the computer.
The way it thinks, and the way programs are written.
Anybody can learn Python keywords.
But to learn to program and to write effective solid code regardless of which
programming language that you’re using, that’s another skill entirely.
Now that you have finished this book, you should be able to do a lot of
programs for different situations.
The next step is to keep practicing a lot in order to become a master of
Python.
While programming, sometimes you might think that some things are
impossible to code or that you are not good enough to do them.
But that is not right; you just have to think a lot in order to make it happen.
Also, while programming, you may find that your code or program is not
working, do not worry. Even the smartest people write codes that do not work
at the beginning.
You just have to keep trying.
As you know, nowadays technology is everywhere, and so programming. Our
recommendation is that you should try to code and solve problems of your
daily activities in order to broaden your vision of the world since all
electronics have hundreds and hundreds of lines of codes on them.
I sincerely hope that this book has helped you to get on the road to
accomplishing everything that you want to accomplish in the world of
programming.
Remember going forward that without a doubt, it will not always be easy.
It won’t be even remotely easy.
Programming is made difficult by its very nature. Humans, we just don’t
think like computers.
But hopefully, I’ve helped you to understand programming, at least.
DATA SCIENCE WITH PYTHON
Introduction
Python is termed as a multi-paradigm language used for programming and
can be perceived as a Swiss army knife in the field of coding.
It can support OOP, functional programming patterns, and structured
programming, among several other things.
There is a saying popularly used in the community of Python, and it goes like
this: Python is normally the 2nd best language for all purposes.
But this isn’t a knock for organizations faced with the dilemma of using the
best of the breed solutions as they soon find themselves burdened with
codebases that are unmaintainable and incompatible.
Python is capable of handling all the jobs from data mining to website
building to the running of embedded systems.
It is an all-in-one programming language.
For instance, in the case of ForecastWatch, Python was utilized for writing a
parser for harvesting forecasts from other sites.
It is also used for an aggregate engine that compiles the data and the website
code for displaying results.
It was PHP, which was originally utilized for building the website until the
organization realized that it was a lot easier to deal with a single language for
everything.
Facebook also selected Python for data analysis because it was being used a
great deal for other portions of the organization.
The name Python is derived from the popular rock band Monty Python.
The creator of the Python programming language, Guido Van Possum, chose
this name to suggest that its use would be fun.
You will find many obscure Monty Python sketches, which are referenced in
the code samples used in Python and those used for documentation.
For these reasons, this is a cherished programming language among
programmers.
The data scientists with scientific or engineering backgrounds might feel like
a barber armed with an ax when they use the language for the first time for
data analysis—out of place.
However, the inherent simplicity and readability of Python make it
comparatively easy to pick, and the quantity of devoted analytical libraries
available nowadays mean that data scientists in all sectors can find packages
tailored for their needs, easily available on the net for downloads.
Due to the general nature of Python and its extensibility, it was inevitable that
as the popularity of the language went into an orbit, its use in the field of data
science became a foregone conclusion.
As a matter of fact, Python is a—jack of all trades—program, and it isn’t
particularly well-suited for statistical analysis.
However, several companies have invested in Python, realizing the
advantages of using a standardized language and extending it for those
purposes.
Effectiveness of Libraries for Python
Similar to other programming languages, the main reason for the success of
Python is the libraries.
There are around 72,000 of them available with the PyPi (Python Package
Index), and the number is constantly rising.
Python is specifically designed to possess a stripped-down and lightweight
core, and its standard library is built by using tools that can be utilized in all
programming tasks.
Python comes with a “batteries included” philosophy that allows its users to
get down to the issue of finding solutions to problems quickly without having
to go across many competing function libraries.
There Is Always Someone Available to Help in the
Python Community
There are many great things about Python, and one of them is the broad and
diverse base of millions of Python users all across the globe who are ready to
offer suggestions and advice when you’re stuck on something.
There is a very good chance that someone else was stuck on the same
problem before you.
These open source communities are extremely popular due to their open
discussion attitude.
However, some of them are pretty fierce about not allowing newcomers to
mix easily.
Python is, happily, an exception.
These Python experts are happy to aid you, both online and during the local
meet-ups.
Chances are, you will stumble into several intricacies of learning a new
programming language.
As Python plays such a vital role in the data science community, you can find
several resources that are specific to the use of Python in the data sciences.
These meet-up groups of data scientists who use Python are prevalent all
across the US, especially in places such as Los Angeles and Seattle.
In case you’re having trouble locating a meet-up group near you that has the
right qualifications, there is a data science hack that uses Python for
searching these meet-up groups to find the perfect match.
Chapter 1: What Is Data Science?
The first thing that we need to take some time looking over in this guidebook
is the basics of data science.
Data science, to keep things simple, is the detailed study of the flow of
information from the huge amounts of data that a company has gathered and
stored.
It is going to involve obtaining some meaningful insights out of raw and
usually unstructured data that can then be processed through analytical
programming and business skills.
Many companies are going to spend a lot of time collecting data and trying to
use it to learn more about their customers, figure out how to release the best
product, and learning how to gain a competitive edge over others.
While these are all great goals, just gathering the data is not going to be
enough to make it happen.
Instead, we need to be able to take that data, and that data is usually pretty
messy and needs some work and analyze it so that we are better able to
handle all that comes with it.
The Importance of Data Science
In a world that is going more and more to the digital space, organizations are
going to deal with unheard of amounts of data, but structured and
unstructured, on a daily basis.
Evolving technologies are going to enable some cost savings for us, and
smarter storage spaces to help us store some of this critical data.
Currently, no matter what kind of industry we are looking at or what kind of
work the company does, there is already a huge need for skilled and
knowledgeable data scientists.
They are actually some of the highest-paid IT professionals right now, mainly
because they can provide such a good value for the companies they work for,
and because there is such a shortage of these professionals.
The gap of data scientists versus the current supply is about 50 percent, and it
is likely to continue growing as more people and companies start to see what
value data science can have for them.
So, why is data becoming so important to these businesses?
In reality, data has always been important, but today, because of the growth
in the internet and other sources, there is an unprecedented amount of data to
work through.
In the past, companies were able to manually go through the data they had,
and maybe use a few business intelligence tools to learn more about the
customer and to make smart decisions.
But this is nearly impossible for any company to do now thanks to the large
amount of data they have to deal with on a regular basis.
In the last few years, there has been a huge amount of growth in something
known as the "Internet of Things", due to which about 90 percent of the data
has been generated in our current world.
This sounds even more impressive when we find out that each day, 2.5
quintillion bytes of data are generated and used, and it is more accelerated
with the growth of the IoT.
This data is going to come to us from a lot of different sources, and where
you decide to gather this data is going to depend on your goals and what you
are hoping to accomplish in the process.
Some of the places where we are able to gather this kind of data will include:
Sensors are used in malls and other shopping locations in order to
gather more information about the people who shop there.
Posts placed on various social media sites.
Digital videos and pictures are captured on our phones.
Purchase transactions that are made through e-commerce.
These are just a few places where we are able to gather up some of the data
that we need and put it to use with data science.
And as the IoT grows and more data is created on a daily basis, it is likely
that we are going to find even more sources that will help us to take on our
biggest business problems.
And this leads us to need data science more than ever.
All of this data that we are gathering from the sources above and more will be
known as big data.
Currently, most companies are going to be flooded and a bit overwhelmed by
all of the data that is coming their way.
This is why it is so important for these companies to have a good idea of
what to do with the exploding amount of data and how they are able to utilize
it to get ahead.
It is not enough to just gather up the data.
This may seem like a great idea, but if you just gather up that data, and don’t
learn what is inside of it, then you are leading yourself to trouble.
Once you can learn what information is inside of that data, and what it all
means, you will find that it is much easier to use that information to give
yourself the competitive advantage that you are looking for.
Data science is going to help us to get all of this done.
It is designed to make it easier for us to really take in the big picture and use
data for our needs.
It will encompass all of the parts of the process of getting the data to work for
us, from gathering the data to cleaning it up and organizing it, to analyzing it,
to creating visuals to help us better understand the data, and even to the point
of how we decide to use that data.
All of this comes together and helps us to really see what is inside of the data,
and it is all a part of the data science process.
Data science is going to work because it is able to bring together a ton of
different skills, like statistics, mathematics, and business domain knowledge,
and can help out a company in many ways.
Some of the things that data science is able to do when it is used in the proper
manner for a company, will include some of the following:
Reduce costs.
Get the company into a new market.
Tap into a new demographic to increase their reach.
Gauge the effectiveness of a marketing campaign.
Launch a new service or a new product.
And this is just the start of the list.
If you are willing to work with data science and learn the different steps that
come with it, you will find that it is able to help your business out in many
different manners, and it can be one of the best options for you to use in order
to get ahead in your industry.
How Is Data Science Used?
One of the best ways to learn more about data science and how it works is to
take a look at how some of the top players in the industry are already using
data science.
There are a ton of big-name companies who are already relying on data
science to help them reach their customers better, keep waste and costs down,
and so much more.
For example, some of the names that we are going to take a look at here
include Google, Amazon, and Visa.
As you will see with all of these, one of the biggest deciding factors for an
organization is what value they think is the most important to extract from
their data using analytics, and how they would like to present that
information as well.
Let’s take a look at how each of these companies has been able to use data
science for their needs to see some results.
First on the list is Google.
This is one of the biggest companies right now that is on a hiring spree for
trained data scientists.
Google has been driven by data science in a lot of the work that they do, and
they also rely on machine learning and artificial intelligence in order to reach
their customers and to ensure that they are providing some of the best
products possible to customers as well.
Data science and some good analysis have been able to help them get all of
this done effectively.
Next on the list is the company Amazon.
This is a huge company known around the world, one that many of us use on
a daily basis.
It is a cloud computing and e-commerce site that relies heavily on data
scientists to help them release new products, keep customer information safe,
and even to do things like providing recommendations on what to purchase
next on the site.
They will use the data scientist to help them find out more about the mindset
of the customer and to enhance the geographical reach of their cloud domain
and their e-commerce, just to name a few of their business goals right now.
And then, we need to take a look at the Visa company and what they are
doing with the help of data science.
As an online financial gateway for countless other companies, Visa ends up
completing transactions that are worth hundreds of millions in one day, much
more than what other companies can even dream about.
Due to the large number of transactions that are going on, Visa needs data
scientists to help them increase their revenue, check if there are any
fraudulent transactions, and even to customize some products and services
based on the requirements of the customer.
The Lifecycle of Data Science
We are going to go into more detail about the lifecycle of data science as we
progress through this guidebook, but first, we can take a moment just to see
how we are able to use this for our own needs.
Data science is going to follow our data from the gathering stage of the data,
all the way through until we use that data to make our big business decisions.
There are a number of steps that are going to show up in the process in the
meantime, and being prepared to handle all of these, and all that they entail,
is the challenge that comes when we want to rely on data science.
Some of the basic steps that are found in the data science lifecycle are going
to include:
Figuring out what business question we would like to answer with this
process.
The process of collecting raw data for use.
Cleaning and organizing all unstructured data to be used.
Preprocessing our data.
Creating a model with the help of machine learning and taking some
time to train and test it to ensure accurate results along the way.
Running our data through the model to help us understand what
insights and predictions are inside.
Use visuals to help us better understand the complex relationships that
are found in any data that we are using for this analysis.
While the steps may sound easy enough to work with, there are going to be
some complexities and a lot of back and forth that we have to work with here.
The most important thing here is to go into it without any preconceived
notions of what you would like to see happening and don’t try to push your
own agenda on the data.
This is the best way to ensure that you will actually learn what is inside of
that data and can make it easier to choose the right decisions for your needs
as well.
The Components of Data Science
Now, we also need to take some time to look at the basics of data science.
There are going to be a few key components that come into play when we are
talking about data science, and having these in place is going to make a big
difference in how well we are able to handle some of the different parts that
come with data science, and how we can take on some of the different parts
that we need with our own projects.
Some of the key components that we need to take a look at when it comes to
data science will include:
The Various Types of Data: The foundation of any data science
project is going to be the raw set of data. There are a lot of different
types. We can work with the structured data that is mostly found in
tabular form, and the unstructured data, which is going to include PDF
files, emails, videos, and images.
Programming: You will need some kind of programming language to
get the work done, with Python and R being the best option. Data
management and data analysis are going to be done with some
computer programming. Python and R are the two most popular
programming languages that we will focus on here.
Statistics and Probability: Data is going to be manipulated in different
ways in order to extract some good information out of it. The
mathematical foundation of data science is going to be probability and
statistics. Without having a good knowledge of probability and
statistics, there is going to be a higher possibility of misinterpreting the
data and reaching conclusions that are not correct. This is a big reason
why the probability and statistics that we are looking at here are going
to be so important in data science.
Machine Learning: As someone who is working with data science,
you are going to spend at least a little time learning the algorithms of
machine learning on a daily basis. This can include methods of
classification and regression. It is important for a data scientist to know
machine learning to complete their job, since this is the tool that is
needed to help predict valuable insights from the data that is available.
Big Data: In our current world, raw data is going to be what we use to
train and test our models and then figure out the best insights and
predictions out of that data. Working with big data is going to help us
to figure out what important, although hidden, information is found in
our raw data. There are a lot of different tools that we are able to use in
order to help us not only find the big data but also to process some of
these big data as well.
There are many companies that are learning the value of data science and all
that is going to come with it.
They like the idea that they can take all of the data they have been collecting
for a long period of time and put it to use to increase their business and give
them that competitive edge they have been looking for.
In the rest of this guidebook, we are going to spend some time focusing on
how to work with data science and all of the different parts that come with it
as well.
Chapter 2: Basics of Python
Python IDEs
An Integrated Development Environment is a tool that provides facilities like
build automation, testing, code lining, and debugging for different
programming languages.
Python IDEs are best suited for developing machine learning and deep
analytics models.
Here are some of the best IDEs for Python programming:
Sublime Text
Sublime Text is an amazing code editor that provides high customizability
and is best for beginners.
Along with other popular programming languages, Sublime Text also
supports Python execution and comes with predefined support for the
language.
The editor can be downloaded free of cost and is considered a full-fledged
Python development environment.
Sublime Text packages are written in Python programming language, which
provides a wide range of extensions and packages to support complex
programming.
Atom
Atom is an open-source integrated development environment designed and
developed by Github.
Users can download and install the IDE along with predefined development
packages such as linter-flake8 and python-debugger.
Being highly customizable, users can install packages and set up the
environment to meet their development requirements.
Eclipse
Eclipse is an all-rounder integrated development environment that is
available for Windows, Linux, and OS X.
The tool has a rich marketplace of add-ons and extensions, which makes it
suitable for machine learning and Python development.
Furthermore, the PyDev extension allows the developers to perform Python
debugging and utilize code completion facilities as well.
Getting Started with Python
Basic Syntax
For writing your first Python program, you are required to be well aware of
the basic syntax and requirements of the Python programming language.
A Python program can be written and executed in two basic modes, which
are known as Interactive mode and Script mode.
In the Interactive mode, developers are supposed to write a program and
execute it, whereas, in the Script mode, files and code can be saved and
accessed through the Python program (.py file).
Identifiers
Identifiers are used to identify a module, class, function, or variable in a
program.
In the Python programming language, an identifier can be a letter from A to Z
or from a to z followed by zero or more digits, underscores, or letters.
Furthermore, the Python language does not allow characters such as %, $, or
@ within identifiers.
Being a case-sensitive language, programmers need to place identifiers
carefully to execute the program without any error.
Python syntax can be executed by writing the following line in the command
line:
>> print(“Hello world!”)
Hello world
Variables and Data Types
Similar to other major programming languages such as Java, C, and C++,
Python has predefined data types and rules for using variables.
For Python programming, you must remember that a variable can have both
short and descriptive variables like x, y, age, or year.
A variable name should always start with a letter and cannot start with a
number.
Moreover, variable names are case-sensitive in Python, and developers need
to be careful when declaring variables in the program.
Data Types
Python has built-in default data types, which include text, numeric, sequence,
mapping, Set and Boolean and Binary type.
To get the data type in the Python programming language, the “type()”
function can be used in the program.
Here are some examples of setting data types in Python:
Sample Data Type
x = “ Python” Str
x=5 Int
x = 5.0 float
x = range (5) range
Line Chart
The Matplotlib library allows the development of a line chart by applying the
plot method.
Still, it is possible to create multiple columns using a single graph by plotting
and looping every column on the same axis.
Histogram
By using Matplotlib, you can design a histogram using the hist method.
In case you relay categorical data like column points, it will help determine
the likelihood of each class happening.
Bar Chart
In case you want to show data in a bar chart, then the bar function is useful.
The bar chart is not automatically created using the frequency of a category,
so you will require to use Pandas to achieve this.
The bar chart is useful for grouping data that doesn’t spread categories
because it can become messy.
Visualization Using Pandas
Pandas represent an advanced level of open-source libraries.
It is a simple library that represents data structures and data analysis tools.
Visualization, with the help of Pandas, makes it easy to create data frames
and series.
Still, it has an advanced level of API than the Matplotlib.
As a result, the minimum code is required for similar results.
If you want to install Pandas, then you require to run the pip command.
The Objective of Visualization
Data communication and exploration are the major focus of data
visualization.
Once data is visualized, the patterns become visible.
You will immediately tell whether there is an increasing trend or the relative
magnitude of something in connection to other factors.
Rather than tell people the long list of numbers, why not display the numbers
to them for better clarity?
For instance, let’s consider the worldwide trend search on the word ‘bitcoin.’
You should see that there is a temporary rise in the bitcoin interest, but it
starts to decrease after the peak.
Overall, during the peak interval, there’s a huge hype connected to the
technological and social effects of bitcoin.
Again, the following hype decreases because people understand it, or it’s a
common thing related to hypes.
No matter the situation, data visualization helps us to determine the patterns
in a very clear style.
Keep in mind the importance of data visualization is to explore data.
In the following case, you can quickly choose the patterns as well as the data
send to us.
This is critical when you submit it to the public audience.
Others may decide to go for a quick brief of the data without rushing into
detail.
You don’t really need to disturb them with texts and numbers.
What presents a wide effect is the way you build them using numbers and
texts.
What sets a big difference is how you define the data so that individuals can
quickly recall its importance.
This is where data visualization becomes helpful to allow people to mine data
and communicate whatever you are trying to speak.
There are numerous methods of visualizing data.
The Simplest Method to Complex Visualization of Data
Visualizations are a powerful skill that every data scientist needs to be aware
of to create excellent data.
It is more than just creating beautiful charts, representing the dataset’s
information in a way that is easy for individuals to learn.
When you have the right visualization, an individual can quickly learn the
patterns and information that is found beneath the data.
In the early stages of a project, you will conduct an exploratory data analysis
to generate insights into your data. Creating visualizations will increase your
analysis.
At the end of your project, it is vital to submit your final results in a brief and
compelling manner such that any audience can be able to read.
There’s no doubt your visualizations to the next stage will let you defeat your
next presentation.
This section will explore ways in which you can define an attractive, complex
data visualization.
You will apply the Plotly python library that is excellent in creating
interactive visualizations.
Overview of Plotly
Plotly represents an interactive, browser-depended graphic Python library.
It is a library that allows you to improve the visualization capabilities
compared to the standard Matplotlib.
There are two benefits of applying Plotly instead of other Python libraries
such as Matplotlib, Pandas, and Seaborn. That is:
The ease of application.
This will define an interactive plot and other complex graphics.
Performing the same operation using other libraries takes a lot of work.
It provides additional functionalities.
Since Plotly is designed from D3.js, the plotting capability is more powerful
than other plotting libraries.
The Sunburst charts and many more are possible using Plotly.
Building Attractive Plots Using Plotly
Plotly is useful in building fancy plots.
To start, first, let’s import Plotly and its internal graph objects component.
You will also import Pandas to load the dataset.
The following command will create a new tab within your browser with the
plot.
Graph interactivity comes automatically built-in with Plotly.
Box Plots
This time, we will look at the box plots.
The process is quite similar.
For that reason, we are going to define a graph object, store it into a trace,
and then represent it in a browser.
The box plot will feature attractive properties with box plots.
By default, we attain the same zooming, panning, and point of selection.
Now that the box plot exists, if you hover around each box plot, it will reveal
the following:
Median
1st and 3rd quartiles
Min and Max values of the data range
The upper and/or lower fences if there are outliers
Heat Maps
Heat maps are a critical tool for data scientists.
They are effective for displaying the association between multiple feature
variables in a single graph plus the relative significance of each relationship.
To demonstrate the way your Heat Maps can be improved with Plotly, we are
going to create a correlation matrix of the House Prices dataset as a heat map.