Dr. Cho’s Website
Course Materials

Python basics

Dr. Huidae Cho
Institute for Environmental and Spatial Analysis
University of North Georgia

1   Modules

Python has a lot of modules for extending its features. If you have the pip module installed in your Python environment, installing a module is easy. Open cmd.exe in your Python folder and type:

rem install NumPy using pip (rem is comment for cmd.exe)
scripts\pip install numpy

You just installed NumPy. You first have to import a module to be able to use any classes and functions defined in it:

# import NumPy (# is comment for Python)
import numpy
# cos(pi)

OK, it works (hopefully). Now, every time you need a NumPy function, you have to type numpy, which really hurts your fingers! Let’s give an alias to numpy to save typing:

import numpy as np

Much better! What if you don’t need any other classes or functions from numpy but cos and pi? Try this:

from numpy import cos, pi

In the following sections, just assume that you already imported numpy as np whenever you see np.

2   Tuples and lists

Python has two array-like data types: tuple and list. Both data types are very similar, but the main difference is that a tuple is immutable while a list is mutable. Mutable means that individual elements can be modified once a variable is initialized. Let’s see:

# create a tuple
t = (1, 2, 3)
# this is how you access an element in an array (0-based or starts with index 0)
# let's try to modify the first element
t[0] = 10
# size

# repeat the same with a list
l = ['apple', 'orange', 'pear']
l[0] = 'pineapple'

3   Loops

There are two loop controls in Python: for and while. A for loop takes an array-like data type (tuple or list) and iterates each element in it:

# tuple
for i in (1, 2, 3):

# list
for i in [1, 2, 3]:

A while loop tests a condition and loops the block as long as the condition is true:

# prints 1 through 10
a = 1
while a <= 10:
  a = a+1

What about this?

fruits = ['apple', 'orange', 'pear']

for fruit in fruits:

for i in range(0, len(fruits)):

4   Conditionals

Python provides a branching control if, else, and elif:

a = 1
if a == 0:
  print('a is 0')
  print('a is not 0')

if a == 0:
  print('a is 0')
elif a == 1:
  print('a is 1')
  print('a is not 0 or 1')

5   Matrices

Python itself doesn’t support matrix data types and operations natively. We mainly use NumPy for this.

# 3*2 matrix (3 rows and 2 columns)
np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# is equivalent to
np.matrix('1 2 3; 4 5 6; 7 8 9')

# 1*2 matrix (1 row and 2 columns)
np.matrix([1, 2])
np.matrix([[1, 2]])
np.matrix('1 2')

Multiplying two matrices can be done using *:

# A is 2*3
A = np.matrix('1 2 3; 4 5 6')
# B is 3*2
B = np.matrix('10 20; 30 40; 50 60')
# guess its dimension
C = A*B

6   Functions

We already know that it takes two function calls to plot an image using matplotlib:

import matplotlib.pyplot as plt
img = plt.imread('mycalc.jpg')


Let’s define a function to call plt.imshow and plt.show at once:

def showimg(img):


What about mathematical functions?

def fact(x):
  fact = 1
  # range(a, b) returns a, a+1, ... b-1 or all integers in [a, b)
  for i in range(1, x+1):
    fact *= i
  return fact


7   Plotting

7.1   Mathematical functions

We can plot any mathematical functions using matplotlib.pyplot:

import matplotlib.pyplot as plt

# create an array [0, 2*pi] with an interval 0.1
x = np.arange(0, 2*np.pi, 0.1)

# calculate the cosine of x for all elements in x
y = np.cos(x)

plt.plot(x, y)

7.2   Your own function

Let’s define our own function and overlay it on top of the cosine:

def f(x):
  return 0.5*x*np.sin(x)

z = f(x)
plt.plot(x, y, color='red')
plt.plot(x, z, color='blue')

7.3   Quadratic equation

This code plots a quadratic equation:

def f(x):
  # ** is the power function
  return 3*x**2+2*x+1

# derivative of f(x)
def df(x):
  return 6*x+2

# x is a set of real numbers in [-10, 10] every 0.1
x = np.arange(-10, 10, 0.1)
y = func(x)

##### for fun?
# let's plot the straight line touching f(x) at x=5: g(x)=a*x+b
# its slope is df(5) by the definition of derivative
a = df(5)
# both f(x) and g(x) go through (x, f(x)) at x=5 (touching)
# f(x)=g(x)=a*x+b at x=5 => b=f(x)-a*x
b = f(5)-a*5
g = a*x+b

plt.plot(x, y)
plt.plot(x, g)
plt.plot(5, f(5), 'ro')