# | include: false
import numpy as np
import pandas as pd
256852) np.random.seed(
Fundamentals (Need)
![](https://fabienmaussion.info/scipro_ss2018/img/00_messing_python.png)
- Ensure you have a copy of your Learning Portfolio saved on your computer.
- Set up Jupyter Notebooks.
- To submit this chapter’s work in your Learning Portfolio:
- Navigate to the Python Basics (Need) folder in your Learning Portfolio.
- Open the relevant Jupyter Notebook in this folder.
- Incorporate your work in the Jupyter Notebook.
- Commit and push your changes.
- Develop the habit of committing after completing logical portions of the tasks.
- When finished and ready for feedback, commit with the message “COMPLETED!”
What to expect in this chapter
In this chapter, I will quickly introduce some essential basics of Python–just enough to kickstart your journey. By the end of this chapter, you will understand the absolute fundamentals of Python’s syntax. These include how Python uses indentations (spaces, tabs) to identify blocks of code, how to use the dot(.
) and how to extend Python’s abilities by importing packages. I will also share tips on what to remember (or not) so that you know what to watch out for.
1 Functions
Let’s start our Pythonic journey by revisiting the previous section’s Hello World! task by running the following code.
print('Hello world!')
Hello world!
As seen above, you should see the words Hello World!
as the output.
Allow me to highlight a few things in this command.
print()
is a function.
You can think of a function as ‘something’ that does a specific task. In this case, theprint()
function accepts the “Hello world” argument and prints it to the screen.- Parentheses,
()
, always follow a function.
We use these parentheses to pass arguments to the function. Most functions expect arguments; the parentheses are left empty for those functions that don’t require an argument (e.g.exit()
). print()
is a core (in-built) function of Python.
We can also define our own functions. This is an extremely powerful feature, which we will explore later.- The above is an example of what we call code; instructions written using a syntax that a programming language understands.
- A function is ‘something’ that executes a specific task.
- A function may or may not accept arguments.
- We can define our own functions.
2 Python is interpreted
What we refer to as ‘Python’ is really the Python interpreter1.
An interpreter works sequentially, one command at a time. So, for example, the following has two commands.
print('Hello World')
print('Hello World again')
The interpreter stops and complains if there is an error in the command it is currently executing. We will talk more about Python’s complaints, hissy fits and tantrums later.
3 Python is sensitive.
Python is case-sensitive, so Print()
is different from print()
.
This means,
print('Hello World') # This WILL work
'Hello World') # This will NOT work Print(
Python is case-sensitive.
5 = is not the same as ==
You often see =
and ==
used in programming. These mean two very different things.
=
is used to set something equal.= 'Batman' # Make name carry 'Batman' name
==
is used to check if something is equal (i.e., asking a question).== 'Batman' # Tell me if name is equal to 'Batman'? name # Answer: True or False
I will share more details about using these below. For the moment,
=
is not the same as==
.=
assigns a value and==
asks a question.
6 Use if to make decisions
Making decisions based on data is a cornerstone of life and programming. We accomplish this with the if
statement. Specifically, if
can be used to branch the flow of the program. Here is an example.
= 'Batman'
name
if name == 'Batman':
print('Hello Batman!')
else:
print('Hello World!')
A typical if
statement asks a question (i.e., tests a condition) and has something to do if the answer is True
(printing Hello Batman!) and something else (printing Hello World! ) if it is not. Notice the use of :
and indentations (spaces or tabs) to define what to do if the answer is True
and what to do if the answer is False
.
You can use if
to make decisions.
7 Indentations (spaces) are sooo IMPORTANT!
With Python, this code will work:
= 10
x print(x)
However, the following will not work:
= 10
x print(x)
You can understand why there is an error by looking at the structure of the if
statement. Notice that Python uses an indentation to separate the True
and False
‘blocks’. So you cannot use indentations (spaces) indiscriminately as this will confuse Python.
One of the reasons why Python is so easy to read is its use of indentation. Other languages, such as C++ or R, use brackets that can become clunky. For example, the previous statement in R looks like this:
if (name == 'Batman') {
print('Hello Hero | Batman!')
else {
} print('Hello World!')
}
- Indentations play a crucial role in Python; do not use them indiscriminately.
:
is used to designate a block of code.
Don’t mix spaces and tabs!
Make it easy for yourself; just use the tab
key consistently.
8 ‘age’ is English, age is a variable.
Variables are ‘things’ that can hold information. You can give almost2 any name for a variable. However, it is best to provide a name that describes the data it ‘carries’.
For example, we can store a student’s age using the variable a = 24
. However, it is better to write age = 24
. It is even better to write student_age = 24
.
Be careful about mixing up English with variables. For example, there is a difference between the following.
print(age) # Print the value of the variable age
print("age") # Print the English word 'age'
The former tries to print the value of the variable age. The latter will print the English word “age”.
I wrote ‘tries’ earlier because Python will complain if the variable age
has yet to be assigned a value. To get it to work, we need to do something like:
= 10
age print(age)
Note that you can use either matching pairs of ' '
or " "
. However, it is always good to be consistent. Sometimes, it is good to have both because you need to do things like:
print("You're twenty years old.")
You're twenty years old.
9 Brackets
Python uses all three types of brackets ( )
, [ ]
and { }
. Let me show you some quick examples:
Python uses
( )
in calls to function.print('Hello!') # In functions
Python uses
( )
for mathematics.1 + 2) * 5 # For math (
Python uses
[ ]
for lists of data.= [1, 2, 3, 4, 5] # A 1D list py_list = [ # A 2D list py_list_2 1, "A"], [2, "B"], [3, "C"], [4, "D"], [5, "E"] [ ]
Python uses
{ }
to store data in a ‘thing’ called a dictionary.
Here is an example:= { personal_info 'Names': 'Batman', 'Real Name': 'Bruce Wayne', 'Age': 55, 'Affiliation': 'Justice League', 'Universe': 'DC' }
Notice that the dictionary uses a key to identify a value (e.g., ‘Real Name’ \(\rightarrow\) ‘Bruce Wayne’). This is a neat (and super useful) way to store data and quickly access information; for example:
print(personal_info['Real Name'])
Bruce Wayne
10 Giving Python superpowers with Packages
10.1 Some Context
I now like to talk about an essential, super-powerful feature of Python. For this, I will use the example of doing mathematics using Python. Let’s say we want to calculate:
\[ \dfrac{1 \times ((2-3) + 4)^{5}}{6} \]
We can do this by:
1 * ((2 - 3) + 4) ** 5 / 6
40.5
How about \(\sqrt{4}\)?
4) # Will NOT work because
sqrt(# basic Python is limited
Error in py_call_impl(callable, dots$args, dots$keywords): NameError: name 'sqrt' is not defined
Oh, dear! Python cannot calculate square roots! However, this is not a problem because we can imbue Python with newer functionality by using packages. For instance, I can give Python more math skills by using (importing) the math
package.
10.2 Importing the math
package
import math # Adding(importing) the functions
# of the 'math' package
Now we can use the sqrt()
function of the math
module.
4) math.sqrt(
2.0
10.3 Importing the numpy
package
math
is one of many modules that offer the sqrt()
functionality. So let me also import the super useful Numpy
package to use its sqrt()
function.
import numpy as np # Importing Numpy and giving
# it an alias np
# because I am lazy
Now we can also use the sqrt()
function of the Numpy
module. Since I imported it with an alias (np
) I can be lazy and use np
instead of the longer numpy
.
4) np.sqrt(
2.0
10.4 Why so many packages?
You might wonder why we need multiple sqrt()
functions. There are different versions because they have different capabilities and efficiencies. For example, the Numpy
version can handle a list of numbers:
4, 9, 16]) np.sqrt([
array([2., 3., 4.])
We will talk a lot more about Numpy
later. Before we move on, please note that you need to import packages only once(You do not have to teach Python the same thing twice!). Python will remember the functions until you restart the Python interpreter.
- You can give Python ‘superpowers’ by importing packages.
- You must import a package only once.
- There are different ways to import packages (e.g. with or without an ‘alias’).
11 The dot (.)
You often see a dot(“.
”) used in Python (and many other programming languages). This dot is used to indicate ownership! To see how this works, consider the code below.
4)
math.sqrt(4) np.sqrt(
In the first line, we use the sqrt()
function that belongs to the math module. In the second line, we use the sqrt()
function that belongs to NumPy.
Everything in Python (e.g., numbers, letters) has functions and attributes that belong to them. We can access them using the dot. For example, the following will split the sentence into words.
"I am Batman".split()
['I', 'am', 'Batman']
However, the following will not work because having a split()
function for numbers makes no sense.
1234.split()
The things that can be accessed using the dot depend on what the dot is attached to. This will become more obvious very quickly as you use Python more. So don’t worry about the details for the moment.
The dot(.
) indicates ownership, and what it can access depends on the context.
4 Comments
You will notice that I wrote additional information (e.g. WILL work or will NOT work) in the above code by inserting a
#
. These are called comments.#
and the end of the line constitutes the comment.Here is another example of writing comments.
It is important to note that comments are for you and me (i.e., humans). However, you must use them carefully; unnecessary comments create clutter and hinder code readability. For instance, the following comment is redundant.
Unless you possess an infallible memory, you will definitely forget what the code is meant to do in a day or two (or faster). So, write comments to help your future self understand the purpose of the code. You will develop a knack for writing good comments as you gain more experience. For the moment:
Use comments to emphasize the purpose of the code.