Introduction To Python Course Notes 365 Data Science
Introduction To Python Course Notes 365 Data Science
Intro to Python
2
Table of Contents
Abstract .............................................................................................................4
1. Introduction to Programming ..............................................................................5
2. Why Python?.........................,. ..........................................................................5
3. Python Variables and Data Types. ......................................................................6
3.1 Variables ....................................................................................................6
3.2 Numbers and Boolean Values. ..................................................................... 7
3.3 Strings. ..................................................................................................... 8
4. Basic Python Syntax......................................................................................... 10
4.1 Arithmetic Operators. .............................................................................. 10
4.2 The Double Equality Sign. .......................................................................... 11
4.3 Reassign Values. ....................................................................................... 11
4.4 Add Comments. ....................................................................................... 12
4.5 Line Continuation. .................................................................................... 12
4.6 Indexing Elements. .................................................................................... 13
4.7 Structure Your Code with Indentation. ......................................................... 14
4.8 Comparison Operators. ............................................................................ 14
4.9 Logical Operators. .................................................................................... 15
4.10 Identity Operators. .................................................................................15
5. Conditional Statements. .................................................................................16
5.1 Introduction to the IFstatement. ................................................................... 16
5.2 Add an ELSE statement. ............................................................................ 17
5.3 Else if, for Brief – ELIF.................................................................................. 18
5.4 A Note on Boolean Values.......................................................................... 19
6. Functions. .................................................................................................... 20
6.1 Defining a Function in Python...................................................................... 20
6.2 Creating a Function with a Parameter ......................................................... 21
6.3 print vs. return. ..........................................................................................22
6.4 Using a Function in Another Function. .......................................................... 23
6.5 Creating Functions Containing a Few Arguments. ......................................... 23
6.6 Notable Built-In Functions in Python. ........................................................... 24
3
7. Sequences. ....................................................................................................25
7.1 Lists. .......................................................................................................26
7.2 Help Yourself with Methods. ........................................................................26
7.3 List Slicing. ...............................................................................................27
7.4 Tuples. ....................................................................................................28
7.5 Dictionaries. ............................................................................................29
8. Iteration. .......................................................................................................30
8.1 For- Loops. ...............................................................................................30
8.2 While- Loops and Incrementing. ..................................................................31
8.3 Create Lists with the range() Function. ..........................................................32
8.4 Use Conditional Statements and Loops Together ..........................................33
8.5 All In - Conditional Statements, Functions, and Loops. ....................................33
365 DATA SCENCE 4
Abstract
Python is one of the most widely used programming languages among data
scientists. This course will show you the technical advantages it has over other
programming languages. You will start working with its modules for scientific
computing, and you will begin to understand why these functionalities make Python
the preferred choice in finance, econometrics, economics, data science, and machine
learning.
You will learn about Python’s technical advantages, specific features, modules,
functionalities, and more:
• Basic Python Syntax
• Create and Use functions
• Work with variables, operators, and conditional statements
• Study Python sequences and iterations
• Import modules in Python
Keywords: Python, conditional statements, import modules, python syntax, strings, for
loops, while loops
365 DATA SCENCE 5
1. Introduction to Programming
Term Definition
2. Why Python?
Term Definition
3.1 Variables
One of the main concepts in programming is variables. They are your best friends.
You will deal with them all the time. You will use them to store information. They will
represent your data input.
Let’s say you want to have a variable x that is equal to the value of 5 and then ask the
computer to tell you the value of that variable. Type x equals 5.
Write x and then execute. And here’s the result – 5.
An alternative way to execute the instruction that will provide the value we assigned to
y would be to use the print command.
If we say “print(y)”, the machine will simply execute this command and provide the
value of y as a statement.
365 DATA SCENCE 7
When programming, not only in Python, if you say that a variable has a numeric value,
you are being ambiguous. The reason is that numbers can be integers or floating
points, also called floats, for instance.
Term Definition
Floating point (float) Real numbers. Hence, they have a decimal point
Example: 4.75, -5.50, 11.0
3.3 Strings
An alternative way to do that would be to leave the quotes on the sides and place a
back slash before the apostrophe within the phrase. This backslash is called an escape
character, as it changes the interpretation of characters immediately after it.
To state “press “Enter””, the outer symbols must differ from the inner ones. Put single
quotes on the sides.
365 DATA SCENCE 9
Say you wish to print “Red car” on the same line. “Add” one of the strings to the
other by typing in a plus sign between the two. Put a blank space before the second
apostrophe of the first word.
(In [17])
Type “print ‘Red’”, and then put a comma, which is called a trailing comma, and
Python will print the next word, ‘car’, on the same line, separating the two words with a
blank space. (In [18])
365 DATA SCENCE 10
In the equation you see here, 1 and 2 are called operands, The plus and minus signs
are called operators, and given they also represent arithmetic operations, they can be
called arithmetic operators.
Operator Description
+ Addition
- Subtraction
/ Division
Note: If you want to divide 16 by 3, when you use
Python 2, you should look for the quotient of the
float 16 divided by 3 and not of the integer 16
divided by 3. So, you should either transform the
number into a float or type it as a float directly.
% Returns remainder
* Multiplication
Comments are sentences not executed by the computer; it doesn’t read them as
instructions. The trick is to put a hash sign at the beginning of each line you would like
to insert as a comment.
If you would like to leave a comment on two lines, don’t forget to place the hash sign
at the beginning of each line.
You might prefer to send part of the code to the next line. So, 2.0 times 1.5 plus 5
could be written in two lines, and the machine could still read it as one command. This
could be achieved by putting a back slash where you would like the end of the first
line to be. It indicates you will continue the same command on a new line.
365 DATA SCENCE 13
Note:
Make sure you don’t mistake brackets for parentheses or braces:
parentheses – ()
brackets – []
braces– {} !
A very important thing you should remember is that, in Python, we count from 0, not
from 1! 0, 1, 2, 3, 4, and so on. That’s why I’ll ask for the 4th letter, ‘d’, by writing 3 here.
365 DATA SCENCE 14
The way you apply indentation in practice is important, as this will be the only way to
communicate your ideas to the machine properly.
Def and Print form two separate and, written in this way, clearly distinguishable blocks
of code or blocks of commands.
Everything that regards the function is written with one indentation to the inside. Once
you decide to code something else, start on a new line with no indentation. The blocks
of code are more visible, and this clarifies the logic you are applying to solve your
problem.
Operator Description
Briefly, the logical operators in Python are the words “NOT”, “AND”, and “OR”. They
compare a certain amount of statements and return Boolean values – “True” or “False”
– hence their second name, Boolean operators.
Operator Description
You must respect the order of importance of these three operators. It is: “not” comes
first, then we have “and”, and finally “or”.
The identity operators are the words “is” and “is not”. They function similar to the
double equality sign and the exclamation mark and equality sign we saw earlier.
365 DATA SCENCE 16
5. Conditional Statements
The graph could help you imagine the process of the conditionals. Before it
displays the outcome of the operation, the machine follows these logical steps. If
the conditional code is not to be executed because the if-condition is not true, the
program will directly lead you to some other output or, as it is in this case, to nothing.
After any of the two situations, the machine will go to the next black point and will
progress from there on.
365 DATA SCENCE 17
“ELSE” will tell the computer to execute the successive command in all other cases.
Instead of leading to no output, if the condition is false, we will get to an else code.
Regardless whether the initial condition is satisfied, we will get to the end point, so the
computer has concluded the entire operation and is ready to execute a new one.
365 DATA SCENCE 18
If y is not greater than 5, the computer will think: “else if y is less than 5”, written “elif y
is less than 5”, then I will print out “Less”.
Know that you can add as many elif statements as you need.
When it works with a conditional statement, the computer’s task will be to execute
a specific command once a certain condition has been satisfied. It will read your
commands from the if- statement at the top, through the elif-statements in the middle,
to the else- statement at the end. The first moment the machine finds a satisfied
condition, it will print the respective output and will execute no other part of the code
from this conditional.
365 DATA SCENCE 19
Basically, after you insert your if-statement, the computer will attach a Boolean value to
it. Depending on the value of its outcome, “True” or “False”, it will produce one of the
suggested outputs, “Correct” or “Incorrect”.
365 DATA SCENCE 20
6. Functions
To tell the computer you are about to create a function, just write def at the beginning
of the line. Def is neither a command nor a function. It is a keyword. To indicate this,
Jupyter will automatically change its font color to green. Then, you can type the name
of the function you will use. Then you can add a pair of parentheses. Technically,
within these parentheses, you could place the parameters of the function if it requires
you to have any. It is no problem to have a function with zero parameters.
To proceed, don’t miss to put a colon after the name of the function.
Since it is inconvenient to continue on the same line when the function becomes
longer, it is much better to build the habit of laying the instructions on a new line, with
an indent again. Good legibility counts for a good style of coding!
365 DATA SCENCE 21
Don’t forget to return a value from the function. We will need plus_ten(a) to do a
specific calculation for us and not just print something.
In programming, return regards the value of y; it just says to the machine “after the
operations executed by the function f, return to me the value of y”. “Return” plays a
connection between the second and the third step of the process. In other words,
a function can take an input of one or more variables and return a single output
composed of one or more values. This is why “return” can be used only once in a
function.
print() takes a statement or, better, an object, and provides its printed representation
in the output cell. It just makes a certain statement visible to the programmer.
Otherwise, print does not affect the calculation of the output.
Differently, return does not visualize the output. It specifies what a certain function is
supposed to give back.
It’s important you understand what each of the two keywords does. This will help you a
great deal when working with functions.
In with_bonus(w_hours), you can return directly the wage with working hours as an
output, which would be the value obtained after the wage function has been run, plus
50.
365 DATA SCENCE 23
You can work with more than one parameter in a function. The way this is done
in Python is by enlisting all the arguments within the parentheses, separated by a
comma.
You can call the function for, say, 10, 3, and 2. You will get 4.
Just be careful with the order in which you state the values. In this case, we assigned
10 to the variable a, 3 to b, and 2 to c.
Otherwise, the order won’t matter if and only if you specify the names of the variables
within the parentheses.
365 DATA SCENCE 24
When you install Python on your computer, you are also installing some of its built-in
functions. This means you won’t need to type their code every time you use them –
these functions are already on your computer and can be applied directly.
Function Description
7. Sequences
7.1 Lists
You can access the Participants list by indexing the value 1. This means you have
extracted the second of the elements in this list variable [‘Leila’].
In addition, there is a way to get to the last element from your list – start counting from
the end towards the beginning. Then, you’d need the minus sign before the digit and
don’t fall in the trap of thinking we begin enumerating from 0 again! To obtain “Cate”,
you have to write -1.
365 DATA SCENCE 26
Here is the syntax that allows you to call ready-made built-in methods that you do not
have to create on your own and can be used in Python directly.
After the name of the object, which in this case is the “Participants” list, you must put a
dot called a dot operator. The dot operator allows you to call on or invoke a certain
method. To call the method “append”, state its name, followed by parentheses.
To insert the name “Dwayne” in our list, you must put the string “Dwayne” in inverted
commas between the parentheses.
Alternatively, the same result can be achieved by using the .extend() method. This
time, within the parentheses, you’ll have to add brackets, as you are going to extend
the Participants list by adding a list specified precisely in these parentheses.
365 DATA SCENCE 27
Many of the problems that must be solved will regard a tiny portion of the data, and in
such cases, you can apply slicing.
Imagine you want to use the “Participants” list to obtain a second much smaller list that
contains only two names - Leila and Maria. In Pythonic, that would mean to extract the
elements from the first and second position. To access these elements, we will open
square brackets, just as we did with indexing, and write 1 colon 3. The first number
corresponds precisely to the first position of interest, while the second number is one
position above the last position we need.
365 DATA SCENCE 28
7.4 Tuples
Tuples are another type of data sequences, but differently to lists, they are
immutable. Tuples cannot be changed or modified; you cannot append or delete
elements.
The syntax that indicates you are having a tuple and not a list is that the tuple’s
elements are placed within parentheses and not brackets.
The tuple is the default sequence type in Python, so if you enlist three values here, the
computer will perceive the new variable as a tuple. We could also say the three values
will be packed into a tuple.
For the same reason, you can assign a number of values to the same number of
variables. On the left side of the equality sign, add a tuple of variables, and on the
right, a tuple of values. That’s why the relevant technical term for this activity is tuple
assignment.
365 DATA SCENCE 29
7.5 Dictionaries
Each value is associated with a certain key. More precisely, a key and its respective
value form a key-value pair.
After a certain dictionary has been created, a value can be accessed by its key, instead
of its index!
Similarly, as we could do with lists, we can add a new value to the dictionary in the
following way: the structure to apply here is dictionary name, new key name within
brackets, equality sign, and the name of the new value.
365 DATA SCENCE 30
8. Iteration
The list “even” contains all the even numbers from 0 to 20. “for n in even”, colon, which
would mean for every element n in the list “even”, do the following: print that element.
The command in the loop body is performed once for each element in the even list.
365 DATA SCENCE 31
The same output we obtained in the previous lesson could be achieved after using
a while loop, instead of a for loop. However, the structure we will use will be slightly
different.
Initially, we will set a variable x equal to zero. And we’ll say: while this value is smaller
than or equal to 20, print x.
We want to get the loop to end. What is supposed to succeed, the loop body in the
“while” block, is a line of code that specifies a change in x or what has to happen to x
after it is printed. In our case, we will tell the computer to bind x to a value equal to x + 2.
In programming terms, adding the same number on top of an existing variable during
a loop is called incrementing. The amount being progressively added is called an
increment. In our case, we have an increment of 2.
When you need to randomize data points and lists with data points, you can use
Python’s built-in range function.
The stop value is a required input, while the start and step values are optional. If not
provided, the start value will be automatically replaced with a 0, and the step value
would be assumed to be equal to 1.
To specify a step value in a range, the other two arguments must be chosen as well.
range(1,20,2) creates a list with all the odd numbers from 1 to 19 included. It will start
with the number 1, and the list will end with number 19 (which equals the stop value
20 minus 1), stating only the odd numbers.
365 DATA SCENCE 33
You create an iteration that includes a conditional in the loop body. You can tell the
computer to print all the even values between 0 and 19 and state “Odd” in the places
where we have odd numbers.
We use iterations when we have to go through variables that are part of a list.
You can count the number of items whose value is less than 20 in a list. First, define
a function that takes as an argument numbers, where “numbers” will be a certain list
variable. The trick is to create a variable that, so to speak, “departs” from 0. Let’s call it
total.
The idea is that, when certain conditions are verified, total will change its value. This is
why, in such a situation, it is appropriate to call this variable a rolling sum.
More technically, when we consider x in the numbers list, if it is smaller than 20, we will
increment the total by 1 and finally return the total value. This means that, if x is less than
20, total will grow by 1, and if x is greater than or equal to 20, total will not grow. So, for
a given list, this count function will return the amount of numbers smaller than 20.
Copyright 2022 365 Data Science Ltd. Reproduction is forbidden unless authorized. All rights reserved.
Learn DATA SCIENCE
anytime, anywhere, at your own pace.
If you found this resource useful, check out our e-learning program. We have
everything you need to succeed in data science.
Learn the most sought-after data science skills from the best experts in the field!
Earn a verifiable certificate of achievement trusted by employers worldwide and
future proof your career.
$432 $172.80/year
Email: team@365datascience.com