Introduction to Python
This tutorial will walk through a short introduction to Python with emphasis on the neccessary basics for using dmtools and working with images. To get the most out of this tutorial, it is recommeneded to follow along by running all the code snippets yourself.
In the Installation section, you saw how you can open up a Python prompt
in a terminal where you can enter Python commands and run them. Anything more
than a one line command is going to be bothersome to write in a prompt.
Furthermore, it will not be repeatable. The python script addresses these
issues. A Python script is a text file with the
.py extension. We can write
these files in any text editor. This tutorial assumes you are using VS Code
(see Installing VS Code). After creating a Python script, you can run the
script from a terminal with
python hello_world.py. However, there is one
catch: you must be in the directory where the
hello_world.py script is
located. Hence, we need to be able to navigate directories while in a terminal.
In this section, we will create a directory where we will put our Python scripts and create our first script.
First, open up a terminal. Run the command
mkdir scripts to create a
directory called scripts. You can then
cd into it a run
ls to see that
there is nothing in it yet.
(base) Name-Of-Machine:~ Name-Of-User$ ls Applications Library Desktop Movies Documents Music Downloads Public (base) Name-Of-Machine:~ Name-Of-User$ mkdir scripts (base) Name-Of-Machine:~ Name-Of-User$ ls Applications Movies Desktop Music Documents Public Downloads scripts Library (base) Name-Of-Machine:~ Name-Of-User$ cd scripts (base) Name-Of-Machine:scripts Name-Of-User$ ls (base) Name-Of-Machine:scripts Name-Of-User$
Now, let’s create our first Python script! Rather than opening VS Code
in the traditional way you open applications, we will open it from the
terminal. This is because it will automatically put the files we create in the
working directory which will prevent us from running into issues when trying to
run our Python scripts. Make sure you are still in the
code . to open VS Code (don’t close your terminal because you will
need it to run the Python scripts). You will see a file navigation window on
the left. Create a new file called
# hello_world.py print("Hello World!") # Expected Output: # Hello World!
The lines with
# at the beginning are just comments in the Python code. You
do not need to include them but they can give helpful information! Save the
file and try running
python hello_world.py in the terminal.
(base) Name-Of-Machine:scripts Name-Of-User$ python hello_world.py Hello World!
You just created your first Python script! The remainder of this tutorial will walk you through the basics of Python through multiple example Python scripts . Again, it is recommended you follow along by creating and running these scripts. Even better, try modifying them to see if the output changes as you would expect!
We can add, multipy, subtract, and divide numbers quite easily. What if we
want to use some more complex math functions like the sine function? A lot of
these are provided by a package called NumPy (which we will look at much
closer in Working with Images in NumPy). To access these functins, we first need to
import the package with
import numpy as np. We can then use
to apply the sine function to some value. The math package also
provides some useful functions you may want to use like the floor and ceiling
# simple_math.py # addition, subtraction, multiplication, and division print(1 + 1) # 2 print(3 - 1) # 2 print(1 * 2) # 2 print(4 / 2) # 2.0 # exponents print(3**2) # 9 print(9**(1 / 2)) # 3 # math functions from numpy import numpy as np print(np.sin(1)) # 0.8414709848078965 print(np.sin(np.pi / 2)) # 1.0 # math functions from math import math print(math.floor(0.5)) # 0 print(math.ceil(0.5)) # 1
It is often helpful to assign a name to a value. This is called a variable.
In the script below, we set the variable
x to be
y to be
2. We can then use these variables just like they were the values we
assigned them to.
# variables.py x = 1 y = 2 z = x + y print(x + y) # 3 print(y * 2) # 4 print(z) # 3
If we want to do the same command multiple times, we can use a loop. A loop has
for i in range(n) where
n is the number of times we will run
through this loop. The variable
i starts at zero and is incremented by one
every time we run through the loop. The lines of code that are run in every
iteration of the loop make up the loop body. We indent the lines that are in
the loop body.
# loops.py for i in range(5): print(i) x = 0 for i in range(5): x = x + i print(x) # Expected Output: # 0 # 1 # 2 # 3 # 4 # 10
What if we want to run a line of code only if a certain condition holds?
These are called conditional statements. To compare values, we can use
for equals and
!= for not equals. Note that
x = 2 assigns variable
x == 2 returns if
x has value
2 or not. Next,
we need the syntax for boolean operators like and, or, and not. The operator
x & y returns
True if both
True. The operator
x | y returns
True if at least one of
Lastly, we have the syntax for the conditional statement which is
where the body of the conditional statement runs if
body of the conditional statement is denoted with indentation like the
# condition.py x = True y = False print(x == True) # True print(x == False) # False print(x != False) # True print(not x) # False print(x & y) # False print(x & (not y)) # True print(x | y) # True print((not x) | y) # False if True: print('True!') if False: print('This will not print.') if x | y: print('True!')
Sometimes we have a list of values we care about and not just a single value.
We can represent these as a list. For example,
x = [1,2,3] is a list of
three integers. We can then access the value at a certain index with the
i is the index of the value we want. Python is
zero-indexed which means that the first value in a list has index zero. We can
add values to lists with
.append(). We can also add lists together.
# lists.py x = [1, 2, 3] y = [4, 5] print(x) # [1, 2, 3] print(x) # 1 print(x) # 3 x.append(4) print(x) # [1, 2, 3, 4] print(x + y) # [1, 2, 3, 4, 5]
One of the many nice features in Python is called list comprehension. It allows us to initialize a list. It essentially combines the syntax for a list with the syntax for a loop allowing us to define a list with less code.
# list_comprehension.py # without list comprehension x =  # this list is empty for i in range(4): x.append(i) print(x) # [0, 1, 2, 3] # with list comprehension x = [i for i in range(4)] print(x) # [0, 1, 2, 3] y = [i**2 for i in range(4) if i**2 != 4] print(y) # [0, 1, 9]
One of the most important concepts in programming is the function. Functions
allow us to avoid writing the same code multiple times. A function has
parameters or inputs. Sometimes it has an output and other times, it does not.
The notation for a function declaration in Python is
def f(x, y, ...): where
f is the name of the function and
x, y, ... are the function parameters.
Like we have seen before, we use indentation in Python to denote the function
body. This is the code that will be run every time the function is called.
If the function will return a value, we use the keyword
when we want to call the function, we use the notation
f(x, y, ...) where
f is the name of the function and
x, y, ... are the arguments or actual
values we are assigning the parameters of that function.
# functions.py # this function returns something def add(x, y): return x + y x = add(2,3) y = add(7,8) print(x) # 5 print(y) # 15 # this function does not return anything def append_one(x): x.append(1) x = [4, 3, 2] y = append_one(x) print(x) # [4, 3, 2, 1] print(y) # None
That concludes the tutorial! If you want to do something in Python but don’t know the syntax, Stack Overflow is a great resource. It is also a great resource if you get an error message when trying to run your Python script.