New Mexico Tech
Earth and Environmental Science

ERTH 401 / GEOP 501 - Computational Methods & Tools

Lab 3: Python - Lists and flow control

 

Introduction

This lab will introduce lists which are a great way of organizing data. We will also look at flow control and iteration--two essential tools within Python. For this lab, you will only turn in the '.py' scripts--you will not have to explain each step of code. However, you will have to explain all of your code for the Python scripts. This is the only way to demonstrate that you thoroughly understand your code.

Exercise 1: Lists

In the last lab, we talked about integers, floats and strings. Today, we're going to introduce a new data type--the list. Lists can store multiple values (potentially of different types) at once. Try these lines in interactive Python (i.e. start the Python interpreter on the command line like last time).

mylist = [1, 2, 3]
mylist
mylist[0]
mylist[0]+100
mylist[0]+mylist[1]+mylist[2]
mylist[0] = mylist[1]+mylist[2]
mylist

You can also make lists containing different data types and make lists inside of lists (these are called nested lists). Try these lines:

mylist = [77, 'geophysics', 88.5]
type(mylist)
type(mylist[0])
type(mylist[1])
type(mylist[2])
mylist[0]+mylist[2]
nestedlist = [5, 6, [7, 8, 9, 10], 11, [12, 13]]
nestedlist[0]
nestedlist[2]
nestedlist[2][1]
nestedlist[4][1]
mylist+mylist
mylist-mylist

The last line of code causes an error because operations besides + are not supported.

Deliverable 1

To demonstrate that you understand these list operations, make a script which accesses items within a nested list. The line of code you will use to create your list is displayed below. (Note: it would be easier to copy and paste this code than type it out.)

datalist = [[[-174.204754770, 52.209504660], 'AB01'], [[-152.249531000, 58.925958430], 'AB02'], [[-166.541836000, 53.875635000], 'AB03'], [[-110.597476000, 43.674090000], 'AB04'], [[-163.998466000, 54.811342100], 'AB05']]

Now, using list indices:

1) Print the coordinates of station AB01
2) Print the third station ID
3) Print the latitude of AB02

Exercise 2: List Modifications

Items can be added or removed from lists in several ways. Try these commands.

newlist = [10, 30]
newlist[2:2] = [40]
newlist
newlist[3:5] = [50, 60]
newlist
newlist[1:1] = [20]
newlist
newlist.append(70)
newlist
del newlist[3:]
newlist
newlist.remove(10)
newlist
newlist.insert(0, 55)
newlist.insert(2, 40)
newlist
newlist.sort()
newlist

Deliverable 2

For the second deliverable, you will create the same list from deliverable 1 and perform the following actions:

1. Insert the list [[-119.879524000, 34.414907000], 'AB05'] after station AB04
2. Rename the other AB05 station (last element of the list) 'AB06'
3. Remove all the items associated with AB02
4. Print the full list

Output:
[[[-174.204754770, 52.209504660], 'AB01'], [[-166.541836000, 53.875635000], 'AB03'], [[-110.597476000, 43.674090000], 'AB04'], [[-119.879524000, 34.414907000], 'AB05'], [[-163.998466000, 54.811342100], 'AB06']]

Exercise 3: If...(elif)...else statements

Last Monday, we introduced comparison statements. For example, if we defined x = 5 and then typed x > 3, then the program would return True. These comparisons can be used in conditional statements to control the flow of the program. In most programming languages, these take the form of if - else statements, which are the same thing as the diamond shaped conditionals that many of you put in your flow charts in lab. (Note: You can test this code either in Interactive Mode or type it as a script, although it is easier to write it as a script. In Interactive Mode, after you type the first "if" statement, the program will display '...'--this allows you to enter a multi-line statement. Python requires you to indent blocks of code that go into the if / else branches. To indent, use tabs or the same number of spaces).

var = 5
if var > 0:
    print "var is positive"
elif var == 0:
    print "var is equal to 0"
else:
    print "var is negative"

Try the code above several times with both positive and negative values for var. Additionally, try using that code without indentation to see what happens. Remember that if you are writing this as a script, put

#!/usr/bin/env python

at the start of your files and use the command

$> chmod +x filename.py

on the command line (after exiting Vim, or in a separate terminal) to make it executable. Alternitively, you can also write:

$> python filename.py

on the command line. This hands the script filename.py to the Python interpreter to execute it.

Deliverable 3

Write a script which asks the user for a range of latitudes and longitudes. Then you will check three coordinates within a list to see if the coordinates are within the range that was given. If the coordinates are within the range, then you should print the station name. For this exercise, use a smaller version of our list:

datalist = [[[-174.204754770, 52.209504660], 'AB01'], [[-152.249531000, 58.925958430], 'AB02'], [[-166.541836000, 53.875635000], 'AB03']]

To get input from the user, you will use this code:

latmin = float(input("Enter a minimum latitude:"))
latmax = float(input("Enter a maximum latitude:"))
longmin = float(input("Enter a minimum longitude:"))
longmax = float(input("Enter a maximum longitude:"))

After that, you will have to use flow control to determine whether there are any stations within that range of latitudes and longitudes given. There are several ways to solve this program. As long as you get the program to work properly, you will not have any points taken off.

Deliverable 4

Write a script which imports the datetime library and prints a response based on the time. To import the datetime library, you must put this line near the beggining of the script (after #!/usr/bin/env):

import datetime

This command imports the datetime library which enables you to use new commands in Python related to date and time. You can read more about the datetime library here.

Next, you'll use this code:

time = datetime.datetime.now()
time
print time

This code will go into the package datetime on an object called datetime and call the method now() to get the current time and date. Note the difference in output! The first line "time" prints the datetime object with its values indicated, whereas the second line "print time" prints a string that neatly formatted the values of the datetime object into a standard time display.

Read this documentation to learn how to get the hour and assign this value to the variable time:

time = datetime.datetime.now()XXXXX

You will have to replace the 'XXXXX' with the correct syntax to get the hour. You'll be very well served to familiarize yourself with this package! Compared to how time is handled in many other languages (if at all), this is much more comfortable to use (you can, for instance, add and subtract dates).

Once you have imported the hour into the time variable, print a response depending on what the hour is. If is the morning, print "good morning", if it is in the afternoon, print "good afternoon", and if it is at night, print "good night."

Exercise 4: Iteration

One of the most useful tools in programming is the ability to automate repetitive tasks. If, for example, we needed to perform 100s of similar tasks, we can use a "loop" to execute these tasks with a few lines of code instead of typing out everything individually. Python provides two kinds of loops: for and while loops. For loops are counter based and repeat the indented code given in the body until it is repeated a specified number of times. While loops are condition based and iterate until a condition has been met or until the loop is "broken".

Try this example. We will be using a function called range() to generate a list of numbers to iterate over. Here is the documentation if you are interested in learning more.

for num in range(40):
    print num**2

Let's try a for loop where we iterate through a list instead of a range of numbers:

names = ['Joe', 'Billy', 'Sally', 'Jennifer', 'Bob']
for person in names:
    print "Good morning, " + person

Next, we will use a function called enumerate to give indices for each number that we iterate through and assign the index to x and the number to y (e.g. x = 0, y = 50; x = 1, y = 51, etc). Check out the documentation for more information.

for x, y in enumerate(range(50, 100)):
    print x, y

In the first example, we see that we can not only iterate through ranges of numbers, but through any list. In the second example, we use a function called enumerate to give indices for each number that we iterate through and assign the index to x and the number to y (e.g. x = 0, y = 50; x = 1, y = 51, etc).

Deliverable 5

Create a script which iterates through a range of numbers and prints the current number in the loop. Make sure that your script gives this exact output:
(Hint: You may have to use another argument in range, see the documentation above.)

100
110
120
130
140
150

While loops operate differently. They operate until a condition has been met or a break statement has been used. Try this code.

loopnum = 0
while loopnum < 100:
    print loopnum
    loopnum += 1

Note that this is similar to a for-loop, but you're explicitly incrementing your counter by one (you can also replace the one with other increments).

It's easy to make mistakes with the While loop. For example, try this code:

num = 20
while num < 21:
    print num
    num = num - 1

Oops. To exit this loop, you will have to press Ctrl-C. Now try this modification:

num = 20
while True:
    num = num - 1
    if num % 2 == 0:
        print str(num) + " is even"
    if num == 0:
        break

This may seem a bit odd. The "break" puts the condition to abort the loop in the body of the while loop, but sometimes this is quite useful.

Lets try a more complicated example where we use a loop inside of a loop (called nested loops). (Note: don't copy and paste all of these lines at once. This code may work better if you save it as a script in vim.)

limit = int(input("Enter a number:"))
for num1 in range(2, limit):
    num2 = 2
    while (num2 <= (num1/num2)):
        if not(num1%num2): break
        num2 = num2 + 1
    if (num2 > num1/num2) : print str(num1) + " is prime."

Deliverable 6

Create a script which produces the following output with a nested loop:

2
a
b
c
4
a
b
c
6
a
b
c

rg <at> nmt <dot> edu | Last modified: September 11 2017 15:32.