4 - InnovatiCS - Crash Course in Python Programming
4 - InnovatiCS - Crash Course in Python Programming
The computer understands 1s and 0s only. To communicate a real-life problem to the computer, you need to create a specific type of text,
called a source code or a human readable code, that software can read and then process to the computer in 1s and 0s.
Term Definition
programming taking a task and writing it down in a programming language that the
computer can understand and execute
Why Python?
Python is an open-source, general-purpose high-level programming language.
Term Definition
Open-source software (OSS) Open-source means it is free. Python has a large and active
scientific community with access to the software’s source
code and contributes to its continuous development and
upgrading, depending on users’ needs.
General-purpose There is a broad set of fields where Python could be applied
– web programming, analysis of financial data, analysis of big
data, and more.
High-level High-level languages employ syntax a lot closer to human
logic, which makes the language easier to learn and implement.
Python’s popularity lies on two main pillars. One is that it is an easy-to-learn programming language designed to be highly
readable, with a syntax quite clear and intuitive. And the second reason is its user-friendliness does not take away from its
strength. Python can execute a variety of complex computations and is one of the most powerful programming languages
preferred by specialists.
Why Jupyter
The Jupyter Notebook App is a server-client application that allows you to edit your code through a web browser.
Language kernels are programs designed to read and execute code in a specific
programming language, like Python, R, or Julia. The Jupyter installation always comes
with an installed Python kernel, and the other kernels can be installed additionally.
The Interfaces, where you can write code, represent the clients. An example of such a
client is the web browser.
The Jupyter server provides the environment where a client is matched with a
corresponding languages kernel. In our case, we will focus on Python, and a web browser as
a client.
Jupyter’s Interface – the Dashboard
As soon as you load the notebook, the Jupyter dashboard opens. Each file and directory has a check box next to it. By ticking
and unticking an item, you could manipulate the respective object – that means you can duplicate or shutdown a running file.
From the Upload button in the top-right corner, you can upload a notebook into the directory you are in.
You can expand the New button. From the list that falls, you will most likely need to create a new text file, a new folder, or a
new notebook file
Jupyter’s Interface – Prerequisites for Coding
You can access a cell by pressing “Enter”. Once you’ve done that, you’ll be able to see the cursor, so you can start typing code.
Jupyter’s Interface – Prerequisites for Coding
Jupyter’s Interface – Prerequisites for Coding
A markdown cell is a cell that contains strictly documentation - text not executed as a code. It will contain some message you
would like to leave to the reader of the file.
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.
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
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])
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 asafloat directly.
% Returns remainder
* Multiplication
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.
Indexing Elements
Yes, you can do that by using square brackets. And within them, you should specify the position of the letter we would like to be extracted.
Note:
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.
Structure Your Code with Indentation
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.
Comparison Operators
Operator Description
== Verifies the left and right side of an equality are equal
!= Verifies the left and right side of an equality are not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Logical Operators
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
“And” Checks whether the two statements around it are “True”
Example: “True andFalse” leads to False
“Or” Checks whether at least one of the two statements is “True”
Example: “False or True” leads to True
“Not” Leads to the opposite of the given statement
Example: “not True” leads to False
You must respect the order of importance of these three operators. It is: “not” comes first, then we have “and”, and finally “or”.
Identity Operator
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.
Introduction to IF Statement
A prominent example of conditional statements in Python is the “If” statement. What you can use it for is intuitive, but it is very
important to learn the syntax.
Introduction to the IF statement
“Else” will tell the computer to execute the successive command in all other cases.
Add an ELSE Statement
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.
Else if, for Brief - ELIF
A very important detail you should try to remember is the computer
always reads your commands from top to bottom. Regardless of the
speed at which it works, it executes only one command at a time.
Scientifically speaking, the instructions we give to the machine are part
of a control flow. This is something like the flow of the logical thought
of the computer, the way the computer thinks – step by step, executing
the steps in a rigid order.
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”.
Defining a Function in Python
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 а good style of coding!
Creating a Function with a Parameter
People often confuse print and return, and the type of situations when we can apply them.
print vs. return
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.
Creating Functions Containing a Few Arguments
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.
Function Description
type() obtains the type of variable you use as an argument
int() transforms its argument in an integer data type
float() transforms its argument in a float data type
str() transforms its argument in a string data type
max() Returns the highest value from a sequence of numbers
min() Returns the lowest value from a sequence of numbers
abs() Allows you to obtain the absolute value of its argument
sum() Calculates the sum of all the elements in a list designated as an argument
Notable Built-In Functions in Python
Function Description
round (x,y) returns the float of its argument (x), rounded to a specified number of
digits (y) after the decimal point
pow(x,y) returns x to the power of y
len() returns the number of elements in an object
Lists
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.
Help Yourself with Methods
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.
List Slicing
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.
Word of Welcome
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.
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.
Dictionaries
Dictionaries represent another way of storing data.
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.
For Loops
Iteration is a fundamental building block of all programs. It is the ability to execute a certain code repeatedly.
While Loops and Incrementing
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.
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.
Create Lists with the range() Function
range(10) will provide a list of 10 elements, starting from 0, implied after not indicating a start value, and ending at the tenth consecutive
number – 9.
In another cell, if in the “range” function we declare as arguments 3 and 7, for instance, Python will accept 3 as a start
value, and 7 as a stop value of the range. So, we’ll have 4 elements – 3, 4, 5, and 6.
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.
Use Conditional Statements and Loops Together
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.
If x leaves a remainder of 0 when divided by 2, which is the same as to say “if x is even”, then print x on the same line. “Else”, which means
unless x is even, or if x is odd, print “Odd”.
All In – Conditional Statements, Functions, and Loops
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.
Thank you
www.innovatics.ai