AISCIENCES - Introduction To Python For Data Analysis - V0
AISCIENCES - Introduction To Python For Data Analysis - V0
I N TRO DU C T IO N TO P Y TH O N F O R
DA TA A NA LY S IS
Guide for Beginners
AI Sciences Publishing
ii
How to contact us
Please address comments and questions concerning this book
to our customer service by email at:
[email protected]
iii
Table of Contents
What is Python................................................................31
iv
What is Programming? ................................................................ 31
How Useful It Is Really? ............................................................. 31
Why Many Universities are Teaching Python ............................ 32
Clarity & Intuitiveness ............................................................... 32
v
More Examples & Exercises ...................................................... 72
vi
• Do you want to discover, learn and understand the methods
and techniques of artificial intelligence, data science,
computer science, machine learning, deep learning or
statistics?
• Would you like to have books that you can read very fast and
understand very easily?
• Would you like to practice AI techniques?
If the answers are yes, you are in the right place. The AI
Sciences book series is perfectly suited to your expectations!
Our books are the best on the market for beginners,
newcomers, students and anyone who wants to learn more
about these subjects without going into too much theoretical
and mathematical detail. Our books are among the best sellers
on Amazon in the field.
About Us
Our books have had phenomenal success and they are today
among the best sellers on Amazon. Our books have helped
many people to progress and especially to understand these
techniques, which are sometimes considered to be complicated
rightly or wrongly.
The books we produce are short, very pleasant to read. These
books focus on the essentials so that beginners can quickly
understand and practice effectively. You will never regret
having chosen one of our books.
We also offer you completely free books on our website: Visit
our site and subscribe in our Email-List: www.aisciences.net
By subscribing to our mailing list, we also offer you all our new
books for free and continuously.
To Contact Us:
• Website: www.aisciences.net
• Email: [email protected]
Follow us on social media and share our publications
• Facebook: @aisciencesllc
• LinkedIn: AI Sciences
2
From AI Sciences Publishing
3
WWW.AISCIENCES.NET
EBooks, free offers of eBooks and online learning courses.
Did you know that AI Sciences offers free eBooks versions of
every books published? Please subscribe to our email list to be
aware about our free eBook promotion. Get in touch with us
at [email protected] for more details.
4
WWW.AISCIENCES.NET
Did you know that AI Sciences offers also online courses?
We want to help you in your career and take control of your
future with powerful and easy to follow courses in Data
Science, Machine Learning, Deep learning, Statistics and all
Artificial Intelligence subjects.
5
Preface
“For me, data science is a mix of three things: quantitative analysis (for the rigor necessary to
understand your data), programming (so that you can process your data and act on your insights),
and storytelling (to help others understand what the data means).”
―Edwin Chen, Data Scientist and Blogger
6
How to Use This Material?
7
The result will be 5050. Notice that we didn’t perform long
calculations by hand. Just a few lines of code and we’re able to
do a possibly long task. This is just one illustration on the
power of programming. You can see more examples that better
show how to use Python to automate tasks and possibly handle
multiple operations fast.
At first the code above seems intimidating. But Python is
actually intuitive. Just by reading through the code you can
already get an idea of what it does. In the above example, we
initiate the sum to zero and add the numbers from 1 to 100 to
the sum (101 is not included because it’s how Python works).
We then “print” the sum so we can see the output.
In the terminal (the place where we execute code) it might look
something like this:
That white font and black background add a nice touch to what
we’re doing. It makes us feel that we’re finally doing some
programming and software engineering.
Well, it’s a simple example. Later on we’ll be dealing with
dozens of lines of codes. These could be overwhelming at first
because the blocks of code work together to create a final
output (or a series of outputs).
To get the most out of this learning material, always try to
understand what the blocks of code really do. In many cases
8
Python is already intuitive and you can understand even what
others wrote because of the simple and clear syntax (in contrast
to Java, C, Lisp, and other programming languages).
Repetition is also the key. As we build up the concepts, it could
be difficult to track which goes where and how each concept
fits into the whole. That’s why as we make the programs more
complex, we’ll review or briefly mention what the previous
were. This way, we can reinforce your learning and make it
easier for you to catch up.
But first, let’s try to motivate you in learning Python and
programming. This way you’ll know the possible incentives
and possibly get a big picture of how Python will improve your
work.
9
likely to have been encountered and solved the problems
you’re facing now.
For some this commitment to time and effort will be very
discouraging. Good news is this could also challenge you to
take on the enormous task. This book will be the starting point
(and it’s enough to challenge you already). And when you strive
for greatness, programming becomes more fun and stressful.
You’ll finally understand how some programmers wake up in
the middle of the night with a knot in their gut.
10
© Copyright 2017 by AI Sciences
All rights reserved.
First Printing, 2016
ISBN-13: 978-1719247221
ISBN-10: 1719247226
11
Legal Notice:
You cannot amend, distribute, sell, use, quote or paraphrase any part
or the content within this book without the consent of the author.
Disclaimer Notice:
12
To my wife Jannet Danboard.
13
A Quick Example
Can you guess what this code does? As with the earlier
example, it will “work on” the numbers from 1 to 100. The
difference is that instead of adding the numbers, it will check
if a certain number is “Odd” or “Even” (divisible by two).
The line if num%2 == 0 means if the number is divided by 2 and
the remainder is zero, print “Even.” Otherwise, print “Odd”
(what else is there?). This simple example is actually one of the
building blocks of many complex programs for today. For
example, think of how email login works. If what you typed in
as your password matches the one saved in their database, you
get access to your account. Else, you’ll be told to try again or
even get blocked from accessing your account.
This if-else statement will be very useful whenever there’s a
“fork” in the process. Will the program take this particular path
or the other one? What happens if we choose that path?
14
By the way, the result of the above program will be this:
Odd
Even
Odd
Even
Odd
Even
15
Even
Odd
Even
…
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28,
30, 32, 34, 36, 38, 40, 42, 44,
46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70,
72, 74, 76, 78, 80, 82, 84, 86, 8
8, 90, 92, 94, 96, 98, 100]
Counting even numbers:
50
print(even_list)
print("Counting even numbers: ")
print(len(even_list))
17
The Big Picture: Using Python for Data Analysis
18
I bet you’re excited to perform cool and advanced stuff using
Python. Unfortunately, we won’t start there. It will take a while
before you can get to build cool stuff. But you’ll eventually get
there if you finish this book and learn more as you go along.
First, we should set up our tools so we can write code and
execute it. You will download and install modern tools that
modern programmers use every day. This is important because
using quality tools will make learning much easier.
Second, we’ll study the basics so we can form a solid
foundation in Python. We’ll explore how Python works and
what can you do about it. Aside from developing your skill,
mastering the basics will also give your ideas on what’s possible
when using Python and in programming in general.
Now let’s start setting your computer so you can begin
programming.
19
Python Setup
Overview
The goal here is to install tools that will allow you to write code
and enable your computer to read and execute Python.
First is we’ll download and install Anaconda. This way, your
computer will be able to read and execute Python code when
you write it. Second is we’ll install Atom (by Github). We’ll use
this as our text editor so you can write code. We can also use
its Terminal so we can run our program.
20
Choose the Python 3 version and click the green Download
button. Downloading will take a while (400+ or 500+ MB file).
When the download’s finished, you can just do a standard
installation. Double click the file and click next until
everything’s done. For now it’s important that you install it for
one User only (there are issues in multi-user installation). If
there’s an error, you can Google search and find out the
solution (many other users have likely encountered your
problem before).
21
Next is type jupyter notebook next at the blinking underscore:
Press Enter and then wait for your default browser (or a new
browser tab) to open. The result will be like this:
22
Now we’re certain that our installation worked. Later on we’ll
explore more about Jupyter Notebook. It’s very useful when
performing data analysis and keeping track of what we’re
doing. Many instructors use Jupyter Notebook because it’s
truly a notebook wherein you can execute code, analyze data,
include text and notes, graph data, and more (all in one place).
23
Notice the different colors and black background. Atom is one
of the modern tools for programming and more and more
users are switching to it for their web and software
development projects.
To download Atom, visit their page (https://atom.io/) and
click the Download button (I think the page auto-detects your
computer OS).
24
Click File and then go to Settings.
Click + Install (in the left side) and at the top you’ll see Install
Packages. In the search box type “platformio ide” and then
click Install at the top search result (1M+ downloads). This is
for adding a “Terminal capability” into our Atom text editor
(where we can run and execute code without opening another
application).
25
After installing a package inside the Atom. Close Atom and
open it again (to make sure changes have taken effect).
The Welcome Page may appear again. At the bottom right
corner, notice there’s a little plus (“+”) sign there. Hover it and
it will say “New Terminal” hinting you that when you click it,
it will open a Terminal for us.
You can open it anytime by clicking the plus sign (or exit by
clicking the X sign at the top left.
Aside from Platformio IDE, it’s also good to install
autocomplete-python. Go again to File, Settings, +Install, and
search for “autocomplete python.”
Those two packages will make your life a bit easier in learning
how to program. Also, you’ll have more focus on the
programming itself than tweaking the tools.
26
Let’s try working on the terminal and get your feet wet on
programming. Open the terminal inside Atom (click plus sign
at the bottom right corner). Once the terminal is ready, type
“python” on the blink and then hit Enter. You’ll see something
like this:
This is now your interactive shell where you can write and run
Python instructions. Let’s try printing “Hello world!” Type this
into the shell:
print(“Hello world!”)
27
There you go you just got a taste of Python. To exit the Python
interactive shell, just press CTRL + Z and then hit Enter. To
open it again type the “python” on the blink.
Common Mistakes
28
TypeError: must be str, not int
29
also got a taste of running the Python interactive shell in the
Terminal.
In the next chapter let’s discuss what is Python so you’ll be
better enlightened on what can you do with it. We’ll also
provide you an overview of what you’re about to learn in the
succeeding chapters. Let’s start.
30
What is Python
What is Programming?
31
Of course you’ll still learn other languages as you dive deeper
into programming. Also, many programming jobs actually
require a knowledge of a dozen programming languages and
technologies. The good thing here is what you learn from
Python will be easily transferable once you start learning other
programming languages.
Yes there will be differences and other quirks. But the most
important thing is you learn the concepts of programming
including how to translate problems and solutions into lines of
code that your computer can execute.
32
Again and again we’re always mentioning these advantages of
Python. That’s because Python’s clarity can make you focus on
understanding programming instead of the nuances of
computer science.
Later you can always learn other programming languages and
discover for yourself the true strengths of Python (and perhaps
how other languages are superior). But for now, let’s focus on
Python itself and finally take a deeper dive into programming
(especially if you’ve dabbled on programming earlier but no
continuity).
33
Python Level One
Using the Interactive Shell
Let’s open Atom, run the Terminal (click the + sign bottom
left corner), and open the interactive shell (type Python). What
appears should be similar to this:
Now we can start typing beside the >>> and hit Enter to run
simple commands. Let’s start again with using the print
statement.
>>>print(“I am awesome.”)
I am awesome.
>>>print(“I can do this.”)
I can do this.
34
File "<stdin>", line 1
print I am awesome
^
SyntaxError: Missing parentheses in call to 'print'.
Did you mean print(I am awesome)?
35
As before, you can exit the shell by pressing CTRL + Z then
hitting Enter.
What happened and what did the percent sign (%) do? It’s
actually called the modulo operator which simply returns the
remainder. In the above example, what’s the remainder of 12
divided by 7?
36
Let’s play some more. Guess what happens if we do this?
>>>2**3
Or
>>>4+2*3
37
We made it work by converting 4 into a string. This way we
can add them together and combine into a single statement.
But
>>>3.0 + 3.0
6.0
38
3.0
Hence,
>>>float(3) + 3.0
6.0
39
So if you’re using multiple quotes or a combination of single
and double quotes, just make sure you’re properly enclosing
the whole thing.
40
learning foundation. Don’t worry though. Even experienced
programmers make those mistakes and confusion. The key is
just moving forward and it will all make sense later (or not at
all but it still works).
41
Try to guess the answer first before typing them into your
Python interactive shell. You can also play around further and
test things yourself.
42
Python Level Two
In the previous chapter we’ve covered some of the basics
including working on strings, integers, and floats. We did some
simple math operations and played some in the Python
interactive shell.
In this chapter let’s take it a step further and create a real
program. Yes, we’ll write some code, save it, and then run it.
We’ll start with something simple (a few lines of code) and then
as the chapter progresses, we’ll make it a bit longer and more
complex. Let’s start by reviewing the print statement because
this is essential in the succeeding lessons.
Print Statements
>>>print(3*3)
9
>>>print(3)
3
Why use the print statement? It’s one way to know that our
program runs correctly (gives the correct output) when we save
our code and run it. Some programmers also use it a sanity
43
check to see that each step works fine before extending their
code or adding more functionalities to it.
Later we’ll see how useful this is when we save a program and
run it.
Assigning Variables
44
12
>>>y % x
1
45
You can also do this:
>>>x = x + 1
>>>x
10
The latter is shorter and looks cooler. You can choose either
as long as it’s clear to you what it does. Many programmers
choose the latter though because it’s different and makes them
feel more like a programmer.
We can also concatenate strings assigned to variables. Let’s do
it.
>>>firstfood = ‘eggs’
>>>secondfood = ‘ham’
>>>thirdfood = ‘bread’
>>>firstfood + secondfood + thirdfood
‘eggshambread’
46
Seriously you actually know almost everything there is to create
a very basic program. You already know what strings, integers,
and floats are. You also know how to do math operations and
print statements and values. Recently you’ve also learned how
to assign variables and work with them (adding them together
or reassigning them to new values).
Let’s apply them all together by saving our first simple
program. Create a new folder in your Desktop and name it
something like ‘python-book’ (or you can pick any simple
name for it). Next is open Atom, go to File, and click Add to
Project Folder:
Look for your newly made folder and click Select Folder.
47
The folder is empty because we haven’t saved anything in it
yet. To add a file, right click the ‘python-book’ in the Atom
text editor and select New File. Enter the filename you want
and add .py at the end.
48
x = 3
y = 9
print(x + y)
49
What happened was that we ran your Python program and got
a result (printed 12). Our computer understood that 3 and 9
are assigned to x and y respectively. We then requested for an
output by saying print(x + y).
50
That’s it. We wrote some code and executed it by doing
“python filename.py” and we got something. Well, what
happens if we remove the print statement and instead just said
x + y?
x = 3
y = 9
x + y
Run again the program and nothing will appear. That’s because
we haven’t said anything about displaying the result. Print
statements are necessary in running Python programs this way
so you can see something.
Let’s delete what we wrote and start all over again. Then this
time, let’s create something longer and a bit more complex.
firstname = 'Py'
lastname = 'Thon '
multiplier = 2 * 3
51
myname = 'Thon'
age = 25
hobby = 'programming'
52
Comments make code more readable. That’s because you can
use human language to explain your code or describe what it
does. Your computer will ignore (not run) the comments you
made. It’s just for you and possibly other people who will read
your code. Here’s an example:
# This is a comment.
# Comments are ignored by the computer. They won’t run.
# A comment is a single line.
# The goal here is to print numbers from 1 to 10 and
tell if each one is even or odd.
53
Mario
Your name is Mario
54
3. Asks the user his/her age and then store that value in
myAge.
4. Finally, print something like “My name is Mario and I
am 25 years old.”
If you’re stuck you can review this chapter and other related
material. Try solving it first before looking at the answer.
One possible solution:
print(“What is your name?”)
print("What is your name?")
myName = input()
print("How old are you?")
myAge = input()
print("My name is " + myName + " and I am " + myAge +
" years old.")
55
Python Level Three
Comparison Operators
You must be already extremely familiar with equal to, less than,
and greater than. These indicate comparison between two
values. In Python, we make comparisons by using the
following:
Operator Meaning
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
They evaluate to True or False (depends on the values you’re
comparing). Let’s look at some examples by opening our
Terminal so we can quickly test the operators. Open the
Terminal in Atom by clicking the plus sign at the bottom left
corner.
Then we open the interactive shell by typing python. When the
>>> symbol appears, it’s time to test what comparison
operators do:
>>>8 == 8
True
>>>8 > 4
True
>>>8 < 4
56
False
>>>8 != 4
True
>>>8 != 8
False
>>>8 >= 2
True
>>>8 <= 2
False
Only the == (equal to) and != (Not equal to) work on strings.
>, <, >=, <= work on integer and floats.
Many beginners get confused with the = and ==. The
difference is that the first, =, is used for assigning values into a
variable. On the other hand, the == is confirming if two values
are equal.
57
What happened there? Both 8 > 3 and 8 > 4 evaluate to True,
so the end result is True. It was made possible by the Boolean
operator and. Let’s use it again:
>>>8 > 3 and 8 > 9
False
>>>8 > 9 and 8 > 10
Yes it’s confusing and you might not find immediate use to it.
Some programmers still use it though for special cases. It’s
good to get familiar with it because sooner or later you’ll
encounter it again if you get serious with programming.
59
for num in range(1, 101):
if num%2 == 0:
print(“Even”)
else:
print(“Odd”)
60
print("What’s the temperature in your room at night
(in Celsius)?")
roomTemp = int(input())
if roomTemp <= 20 and roomTemp >= 15:
print("Nice. It's easy to fall asleep if that's
your room's temperature.")
else:
print("Perhaps it's too cold or too hot. Not
ideal.")
While Loops
Well, the previous lessons are a bit easy. This is where it really
starts. Many people actually give up when they start
encountering this part.
61
Good thing here is this what separates the curious from the
dedicated ones. It may take some time before it all makes sense.
But along the way something will click and realise it’s really
easy. That’s why you just have to go on and repeatedly read
and apply the lesson until you comprehend the concept.
Anyway, let’s just get started so we can get some progress
already.
Many times in programming, a block of code requires to be
executed over and over as long as the condition holds True. It
can run indefinitely until it meets or exceeds a certain
condition. Let’s illustrate this by creating a whileLoop.py file
and typing in the following:
inbox = 0
while inbox < 10:
print(“You have a message.”)
inbox = inbox + 1
62
You have a message.
You have a message.
You have a message.
You have a message.
You have a message.
Notice that the code ran for 10 times. That’s because the count
started at zero (inbox = 0) which is the first run of the while
loop. For each run, 1 is added to the value of the inbox (second
run the inbox is now equal to 1). This happened again and
again until inbox = 9. Once the value of inbox reached 10, the
code stops because inbox < 10 is now False.
We can illustrate this more easily by typing the following code
into the whileLoop.py file (overwrite existing code):
inbox = 0
while inbox < 10:
print(str(inbox) + " You have a message.")
inbox = inbox + 1
63
8 You have a message.
The count started at zero and ended at 9. This may sound a bit
confusing at first but please endure. You don’t have to
remember everything. You can just first test your code anytime
and see what happens.
In the previous example we made a while loop that stops when
a certain value was met or exceeded (the block of code
terminates when while statement evaluates to False). We can
also get a bit more creative with it by making a seemingly
infinite loop.
name = ''
while name != 'Casanova':
print('Please type your name.')
name = input()
print('Congratulations!')
64
This won’t stop until you enter the name that matches the
code. If you run the code again and typed ‘Casanova’, you’ll
exit the while loop and run the code outside that.
Please type your name.
Casanova
Congratulations!
For Loops
65
64
81
What happened there? The code inside the for loop was
executed from numbers 0 to 9 (the range). Each number was
squared (exponent of 2) when printing the result.
Here’s another example:
total = 0
for num in range(101):
total = total + num
print(total)
When you run this, the print out result will be 5050. Here’s
what happened. First, we initiate a variable equal to zero (total
= 0). Then we created a for loop which will run the numbers
from 0 to 100 (the range feature just excludes 101). Inside the
loop we add each “member of the range” into the total. This
happens repeatedly from 0 to 100. The total then has changing
values because of the consecutive additions.
Once every number in the range was used, the variable total
now has a final value. We then print out the result which yields
to 5050 (the sum of numbers from 0 to 100).
Instead of manually adding the numbers from 0 to 100 (e.g. 0
+ 1 + 2 + 3 + 4 + 5 and so on), we save some time and effort
because we’re using a for loop instead. It’s just a few lines of
code and it just looks savvy.
How useful is this? Remember the example we gave earlier:
even_list = []
for num in range(1, 101):
66
if num%2 == 0:
print("Even")
even_list.append(num)
else:
print("Odd")
print(even_list)
print("Counting even numbers: ")
print(len(even_list))
67
Even
Odd
Even
Odd
Even
Odd
Even
Odd
… (it’s a long result)
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28,
30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54,
56, 58, 60, 62, 64, 66, 68, 70,
72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96,
98, 100]
Counting even numbers:
50
68
failing (Fail). We could also count the number of entries for
each list.
In code it will look something like this (we check how many 4
and 5 star reviews for a book):
all_reviews = [5, 5, 4, 4, 5, 3, 2, 5, 3, 2, 5, 4, 3,
1, 1, 2, 3, 5, 5]
positive_reviews = []
for i in all_reviews:
if i > 3:
print('Pass')
positive_reviews.append(i)
else:
print('Fail')
print(positive_reviews)
print(len(positive_reviews))
ratio_positive = len(positive_reviews) /
len(all_reviews)
print('Percentage of positive reviews: ')
print(ratio_positive * 100)
Save this in a new .py file (e.g. reviews.py). You can then run
the program in the terminal by typing python reviews.py
You should see the results as this:
Pass
Pass
Pass
Pass
Pass
69
Fail
Fail
Pass
Fail
Fail
Pass
Pass
Fail
Fail
Fail
Fail
Fail
Pass
Pass
[5, 5, 4, 4, 5, 5, 5, 4, 5, 5]
10
Percentage of positive reviews:
52.63157894736842
70
Once the loop is finished, we print out the positive_reviews
and see that only ratings higher than 3 appears:
[5, 5, 4, 4, 5, 5, 5, 4, 5, 5]
The result is 10. But this number is not useful in itself. We also
want to know the context like the percentage of positive
reviews. This way we can immediately get an idea if the reviews
are really good (e.g. chance to become an Amazon bestseller?).
We can get the percentage using the following lines of code:
ratio_positive = len(positive_reviews) /
len(all_reviews)
print('Percentage of positive reviews: ')
print(ratio_positive * 100)
71
elif, else), while loops, and for loops. With this set of
knowledge we can already create a simple program that may
guide the user to a series of actions and outputs.
For example, if the user input is equal to the desired input
(saved in the database such as login email and password), the
user could successfully log in and access a certain page.
Another useful application is in fast and large-scale data
analysis. With Python, we can quickly check if a certain number
or dataset falls within a range. We can also save the “passing
values” into a list and determine its count.
Although the examples mentioned above are simple, we
already get an idea about the potential of using Python in data
analysis and other applications. It’s all about interacting with
data or user input. Then, we set the conditions (comparison
operators) and flow (if, else, elif).
Try this another exercise. Predict the result (or explain the
possible results) of this block of code:
72
div_three = []
for i in range(1, 50):
if i%3 == 0:
div_three.append(i)
print(div_three)
73
Python Level Four
This is where it gets really interesting. We’re about to create
programs that resemble the real world ones. This becomes
possible with the use of Functions. It’s like creating mini-
programs within a huge program. That’s because each mini-
program specifically does something and outputs an
intermediary or final result. We’ll discuss later how to
accomplish this.
Aside from Functions, we’ll also discuss Scope (Global &
Local variables) and Errors and Exceptions. It’s important to
learn these so we can create a truly working program without
much confusion. Take note that most valuable Python
programs will have hundreds or thousands of lines of code in
it. It’s crucial that almost everything’s clear both to the original
maker of the code and the succeeding team.
Don’t worry if the later topics won’t make sense or if they’ll
confuse more. After all, they should be. Good news is with
repetition you can get the hang of it. Even experienced
programmers get stuck or they need to review the basics of
Python from time to time.
Well, enough of the motivational talk. After all, it’s just more
motivating to get into action and quickly see the results. Let’s
start with creating mini-programs within a program.
74
hello()
hi_name('Aardvark')
75
def add_numbers(a,b):
print(a + b)
add_numbers(5,10)
add_numbers(35,55)
Can you guess what the above function does? Yes, you’re
correct. Simply, when we call the function we use the numbers
inside and add them. When you run this the results should be:
15
90
square_number(50)
square_number(9)
You’re correct again. Just one look and you know immediately
what it should do. The function will square the number passed
inside when the function is called.
Those are simple examples. What happens if we incorporate
Comparison Operators (==, >, <, etc.) and Flow Control (if,
elif, else)?
def even_check(num):
if num % 2 == 0:
print('Number is even.')
else:
print('Hmm, it is odd.')
76
even_check(50)
even_check(51)
77
x = 25
def printer():
x = 50
return x
print(x)
Save this into scope.py and try to guess the output before
running the code. Notice x is mentioned twice (one before the
function, x = 25 and another inside the function x = 50). What
would Python show?
If you run the code, it will return 25. But what if you call the
function?
print(printer())
79
That’s because errors exist and will appear. Perhaps it’s just a
typo error or we failed to write the code properly. We’re
expecting something but another thing happened (e.g. Local
and Global variables). Here’s an example:
print(‘Hello’
Save this in errors.py and run it. You should see
something like this:
File "errors.py", line 1
print('Hello
^
SyntaxError: EOL while scanning string literal
80
Let’s just look at example to better illustrate this:
def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: Invalid argument.')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
After ‘trying’ the code and detecting an error, the flow will
proceed with the except clause to handle that kind of error.
Instead of stopping the program (or making it crash), it can still
go on. Run this whole code and see what happens:
81
def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: Invalid argument.')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
82
A similar example related to this is when we’re setting a
password. Perhaps the website or app requires a number for
the password to be accepted. If we fail to include a number,
the website should just notify the user that it requires a number
for the password to be valid (and not crash the whole site).
This way, the user can just ‘try’ again until the password
becomes valid.
83
To reinforce and solidify your learning, predict what will
happen if we run this function:
def sum_three(a,b,c):
print(a + b + c)
sum_three(3,4,5)
Once you’ve solved that, now it’s your turn to create your own
function. This time, instead of checking if the number is
divisible by 3, we check if it’s divisible by 5 (Hint: focus on the
if statement).
Let’s also have a review about try and except. Look at the
following code and guess what it does (better though is to type
the code and run it yourself later).
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
84
print("Oops! That was no valid number. Try
again...")
Try entering an integer and then run again the program. But
this time enter a string such as ‘error’. Notice how the code
handles the error.
85
Python Level Five
We’re in the last part of learning the basics of Python. Here
we’ll talk about the list and how to use it. Learning how to
create, modify, and use lists is important in handling data and
sequences.
Actually, we’ve already touched on lists (e.g. remember the for
loops wherein we initiate an empty list?). Here we’ll review
those concepts we discussed earlier and talk more about how
to manipulate lists.
Creating a List
We can even create a list with both strings and numbers in it:
mixed_list = [3.14, ‘circle’, ‘eggs’, 500]
86
Indexing the List Values (starts at 0, not 1)
Now we’ve created some lists, it’s time to ‘access’ the values in
it. This is very useful if we’re only working on a certain value
or we want to change it (more on this later). Let’s look at an
example and open an interactive shell (type python in the end
so >>> appears):
>>>colours = [‘red’, ‘blue’, ‘green’]
Press Enter to save the list. To access and use the first value,
we can do this:
>>>colours[0]
This should show ‘red’ because it’s the first value (indexing
starts at 0, not 1). To access the second value, we can just do
this:
>>>colours[1]
Earlier we’ve learned how to access a single value from the list.
Here we’ll access multiple values (which is often called ‘slicing’
the list). We’ll just be accessing a portion of the list. This is very
useful if we’re only concerned about a list’ certain portion/s.
Here’s an example:
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(my_list[0:2])
print(my_list[1:])
87
print(my_list[3:6])
Save this into list.py and run the program. The result should be
this:
[0, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5]
We can also slice the original list in the middle (or just
somewhere not in the beginning or end). For example,
my_list[3:6] will return:
[3, 4, 5]
The slicing starts at index three and ends at index five (but its
value is not included in the slice). These may all seem
counterintuitive at first but it’s just how Python works.
Just remember that indexing starts at zero. Also, the value of
the second index is not included when doing the slicing.
88
Whenever you’re in doubt, you can always test your code to
see if the output is what you really desired.
Aside from accessing and slicing the list, it’s also important to
get its ‘length’ to see how many values are there in the list. In
the previous chapters we’ve already mentioned this to ‘count’
the contents of a certain or resulting list.
For example, let’s identify the number of values in this list:
my_list = [0,1,2,3,4,5,6,7,8,9]
We can accomplish that by using the len method onto the list:
len(my_list) # or print(len(my_list)) so we can see
the output
89
Notice that colours[0] is originally equal to ‘red’. However, we
can change that by first accessing the value we want to change,
getting the index, and then setting it equal to a new value.
We can also do this to further modify the contents of the list:
colours[1] = 'purple'
colours[2] = 'magenta'
print(colours)
The entire list has changed because we’ve set a different value
to each content. But what happens if we use an index that go
beyond the original list (e.g. perhaps adding another value to
the list)?
colours[3] = 'pink'
print(colours)
Note that the error message shows what we’ve done wrong
here. This gives us a clear clue of what went wrong and what
to do to correct it.
90
Earlier we’re trying to add a new value to a list but the index
for it doesn’t change. In other words, we’re trying to ‘extend’
the list by adding new values. The right way to accomplish this
is by:
colours = ['red', 'green', 'blue']
colours.append('pink')
print(colours)
The result will be:
['red', 'green', 'blue', 'pink']
We ‘appended’ a new value into the list. That new value went
into the end of the list. This is very useful when we’re building
a list as with the case of a for loop we discussed earlier.
even_list = []
for num in range(1, 101):
if num%2 == 0:
print("Even")
even_list.append(num)
else:
print("Odd")
print(even_list)
print("Counting even numbers: ")
print(len(even_list))
91
Aside from append, another useful and common list
operation is concatenation. Simply, this is adding or
combining the values of the lists (or just their slices) to form a
new list. For example:
fave_series = ['GOT', 'TWD', 'WW']
fave_movies = ['HP', 'LOTR', 'SW']
fave_all = fave_series + fave_movies
print(fave_all)
Save this in a fave.py and run it. You should see this:
['GOT', 'TWD', 'WW', 'HP', 'LOTR', 'SW']
Notice that we’re only using the first two values of the first list
and the last two values of the second list. In other words, we
first access the desired portions of the lists and then
concatenating them to form a new one.
92
In this chapter we’ve focused on creating lists and
manipulating them. We saw how to access a certain value or
slice of the list. We also learned how to do common list
operations such as concatenation and append.
There are also other list operations that you may encounter in
the near future. Here are some examples:
list.insert(0, ‘indigo’)
list.extend(‘orange’, ‘violet’)
list.remove(‘pink’)
93
2. Change the second item into ‘spam’.
3. Print the new list.
4. Slice my_list. Show the first four items.
5. Create a new list called ‘your_list’ and add three
different items.
6. Concatenate the my_list and your_list.
These are easy tasks and you can quickly test if you’re doing
them right. A valuable tip here is to write the expected output
first and then write the code. Test and compare the expected
output with what you see in your Terminal or Shell. Make
changes until it’s a full match.
94
Recap and Some Advice
Practice and repetition is the key to learning and understanding
Python (and any other programming language). Some of the
concepts might not make sense at first (or they’ll seem
confusing) but if you endure, something will click and
everything will look clear to you.
Aside from repetition and practice, it’s also recommended to
do some reading of other people’s code (search in Github and
type ‘python’). Try to make sense of the lines of code. As you
gain more experience, you’ll immediately get a clue of what a
block of code does.
Along the way you’ll surely get stuck because of error messages
and perhaps a lack of understanding. It’s normal because
programming is truly a complex task. That’s actually a good
thing because other people have likely encountered the same
error messages and struggles you’ll be dealing with. You’ll
quickly find the answers by using Google and StackOverflow.
Finally, experiment with new approaches about solving a
problem. Perhaps you have a shorter or more efficient way to
accomplish certain programming tasks. You can always test a
block of code and see what it does. The key here is to start
small and test the code right away. This way, you’ll know if
you’re heading into the right direction.
95
Resources
Here are the links and resources we’ve used to complete this
first part of the book:
https://www.python.org/
https://docs.python.org/3/
https://www.anaconda.com/download/
https://atom.io/
https://automatetheboringstuff.com/
https://developers.google.com/edu/python/
https://stackoverflow.com/
https://www.python.org/about/quotes/
97
Thank you !
Thank you for buying this book! It is intended to help you
understanding Python for Data Analysis. If you enjoyed this
book and felt that it added value to your life, we ask that you
please take the time to review it.
hat you please take the time to review it.
Your honest feedback would be greatly appreciated. It
really does make a difference.
If you noticed any problem, please let us know by
sending us an email at [email protected] before
writing any review online. It will be very helpful for us
to improve the quality of our books.
https://www.amazon.com/dp/B07FTPKJMM
98
99
100