Skip to content

Instantly share code, notes, and snippets.

@fgassert
Created January 31, 2017 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fgassert/6873bd4126125eab914bd9d151215b5e to your computer and use it in GitHub Desktop.
Save fgassert/6873bd4126125eab914bd9d151215b5e to your computer and use it in GitHub Desktop.
'''
Created on Jan 26, 2012
@author: Francis.Gassert
'''
'''
Welcome to Python!
Python is a simple scripting language that allows you to harness the power of your computer.
Computers are very good at doing the same thing over and over again.
They are also very good at simple math.
These things are boring to humans, and we make mistakes.
By making the computer do these things for us, we can save time to have more fun.
A lot of these tools already exist; Excel, for example.
However, sometimes the right tool for the job just isn't there.
With Python, you can quickly build the tool you need.
At work, the most common applications I have for Python are repetitive and iterative data processing.
For example, suppose you are collecting water quality data, but you have a separate data file for each site.
Rather than manually extracting the data, you can write a script to do it for you.
Another use for Python is automating and tracking tasks.
When I have a multi-step GIS project, it is simple enough to wallow through the analysis.
However, afterwards it can be difficult to remember exactly what I did.
Using Python to automate the process may not be any faster,
but when you're done, you're left with a step by step set of instructions of exactly what you did.
Moreover, if you made a mistake or your source data change, you can redo the analysis with a click of a button.
'''
'''
1. The variable
Variables hold data: numbers, letters, and objects.
Think of variables as one cell on a spreadsheet.
We name them, so that we can refer back to them easily.
The following code creates three variables: width, height, and area
'''
width = 3
height = 4
area = width * height
'''
The equals sign makes the name on the left hold result of the right.
Variables names can be any combination of letters, digit, and underscores (a-z,A-Z,0-9,_) though the first character can't be a digit,
but you should avoid using special names such as 'print'
Case matters!
'''
a = 5
A = 6
a_2 = a / A
'''
Note: if you want to compare two variables, you must use the double equals sign. Single equals signs are always for assignment.
Comparators: == != > < >= <= (equal, not equal, greater than, less than, greater or equal, less or equal)
'''
a == A
#> False
a = A
a == A
#> True
'''
Variables can also hold text. These are called "strings".
Strings should be enclosed in matching quote marks (single or double),
otherwise the computer will think you're referring to variables with those names
'''
subject = "They"
predicate = "'re called"
object = '"strings"'
punctuation = "."
sentence = subject + predicate + ' ' + object + punctuation
'''
Single quotes and double quotes work identically, so that you can enclose apostrophes or quotes in your strings.
'''
'''
2. The comment
Comments are lines that mean nothing to the script, but are often used to add clarifying or explanatory material.
They also allow you to temporarily remove lines of code from your script without deleting them.
'''
# the following line was removed because it causes a error (the variable <Area> is not defined)
#q = Area
# the following line works!
q = area
'''
Block quotes also function as comments in Python.
Block quotes are started and ended by by three matching quote marks (single or double).
This is a block quote.
'''
'''
3. The print statement
Format:
print <variable>
The print statement is used to output text from the program.
It is often useful to find out what's going on when your program is running.
Outputs are shown in the comments.
'''
print "hello"
#> hello
print sentence
#> They're called "strings".
print area
#> 12
'''
4. The if statement
Format:
if <expression>:
<code block>
The if statement is one of the fundamentals tools of programming.
An if statement evaluates an "expression" such as a comparison of variables.
If the expression is true, then the code block inside the if statement is run.
Otherwise, the code block is skipped.
In Python, you show which lines are inside the if statement by indenting them.
'''
should_i_execute_the_code_block = True
if should_i_execute_the_code_block == True:
#This is inside the if statement
print "executed!"
#This is outside the if statement
print "This happens regardless!"
'''
5. <and> and <or> logical operators
Expressions can be joined using the <and> and <or> logical operators.
Use parenthesis to control the order of operations.
'''
x = False
y = True
z = True
if (x and y) or z:
print "(False and True) or True -> True"
if x and (y or z):
print "False and (True or True) -> False"
'''
6. The if ... elif ... else statement
Format:
if <expression>:
<code block>
...
elif <expression>:
<code block>
...
else:
<code block>
An if statement can be followed by any number of <elif> statements and up to one <else>.
In the simplest form, the <else> is evaluated when the <if> is skipped.
'''
option = 1
# If the variable <option> is equal to 1,
if option == 1:
# do this;
print "1"
else:
# otherwise, do this.
print "Not 1"
'''
Elif statements function as a combination of an else and an if statement.
They only evaluate when the preceding <if> (or <elif>) is skipped.
'''
# exactly one of the following print statements is run.
if option == 1:
print "option 1"
elif option == 2:
print "option 2"
elif option == 3:
print "option 3"
elif option == 4:
print "option 4"
else:
print "None of the above"
'''
7. Lists
Lists are the backbone of Python data management.
A list is a an object that holds any number of other objects in order
Lists are defined with brackets as follows:
'''
thisisalist = ["a","b","c","d"]
'''
Items in a list can be accessed by their index number.
The first item in a list has an index number of zero,
the last item has an index equal to the length of the list minus 1.
You can get parts of a list by using "slices" with a start and end index separated with a colon(:)
'''
thisisalist[0]
#> a
thisisalist[1]
#> b
thisisalist[1:2]
#> ["b","c"]
thisisalist[1:]
#> ["b","c","d"]
# Negative indices indicate to count backward from the end
thisisalist[-2:-1]
#> ["b","c"]
'''
Lists can also contain lists to make two-dimensional matrices
'''
r1 = [1,2,3]
r2 = [4,5,6]
r3 = [7,8,9]
m = [r1,r2,r3]
# m = [[1,2,3],[4,5,6],[7,8,9]]
m[0][0]
#> 1
m[2][2]
#> 9
m[1]
#> [4,5,6]
'''
One can think of items in a list single cells in an Excel workbook,
lists as columns or rows,
lists of lists (2-dimensional) as a sheet,
lists of lists of lists (3-dimensional) as an entire workbook,
and so on.
Lists are also much more dynamic.
Here are a couple useful list functions.
'''
mylist = []
# <list>.append(<value>) adds a value to the end of a list
mylist.append(1)
#> [1]
mylist.append("a")
#> [1,"a"]
mylist.append([10,9,8])
#> [1,"a",[10,9,8]]
# len(<object>) returns the length of a list (or any other object with length such as a string)
len(mylist)
#> 3
len("a string")
#> 8
'''
8. The while loop
Format:
while <expression>:
<code block>
A while loop is like an if-statement.
Except, the contents of a while loop are repeated until the statement is false.
'''
#This loop will repeat forever:
'''
while True:
print "repeat"
'''
#The contents of this loop never execute:
while False:
print "false"
#this loop will repeat five times
i = 0
while i < 5:
print i
i = i + 1
'''
The above loop prints the numbers from 0 through 4.
Of note, the veracity of the while loop expression is checked at the beginning of the loop.
'''
'''
9. The for loop
Format:
for <variable> in <iterator/list>:
<code block>
A for loop is like a while loop with a counter built in.
The most common usage of the for loop uses the "range" function to execute the loop a given number of times
'''
for i in range(5):
print i
#> 0
#> 1
#> 2
#> 3
#> 4
'''
This loop functions identically to the above while loop.
The loop prints the numbers from 0 through 4.
For loops work very will with lists.
'''
country_Names = ["US","Japan","China","Madagascar"]
country_GDP_caps = [46215, 33994, 7536, 961]
for i in range(len(country_GDP_caps)):
print country_Names[i] + " GDP per capita $" + str(country_GDP_caps[i])
#> US GDP per capita $46215
#> Japan GDP per capita $33994
#> China GDP per capita $7536
#> Madagascar GDP per capita $961
'''
NOTE: you must convert numbers into strings before you stick them together with the <+> sign.
Alternatively the above print statement could be written as follows:
print "%s GDP per capita $%s" % (country_Names[i], country_GDP_caps[i])
the <%s>s are replaced by the variables following the <%> sign in the parentheses.
For loops are used to with lists so often that Python lets you iterate through the items of a list directly.
'''
list1 = ["item1", 100, [1,2,3], "a"]
for item in list1:
print item
#> item1
#> 100
#> [1,2,3]
#> a
###############################################################################
'''
A simple program:
This program generates a list of all the prime numbers less than <MAX>.
'''
MAX = 100
primes = []
# count though every number from 2 up to (but not including) MAX.
for x in range(2, MAX):
# for each number, we start by assuming it is prime
is_x_prime = True
# we then check: is it divisible by any of the prime number we have already found?
for p in primes:
# the modulo function <%> gives the remainder of <x> divided by <prime>. If the remainder is zero then is is divisible.
if x % p == 0:
print "%s is divisible by %s" % (x, p)
is_x_prime = False
# the <break> command jumps out of the for loop before it is over.
# if we found a factor, we know x is not prime, so there's no reason to keep searching
break
# if x does not have a prime factor less than its square root, it is prime.
elif p * p > x:
break
if is_x_prime:
print "%s is prime" % (x)
primes.append(x)
print primes
'''
OUTPUT:
2 is prime
3 is prime
4 is divisible by 2
5 is prime
6 is divisible by 2
7 is prime
8 is divisible by 2
9 is divisible by 3
10 is divisible by 2
11 is prime
12 is divisible by 2
13 is prime
14 is divisible by 2
15 is divisible by 3
16 is divisible by 2
17 is prime
18 is divisible by 2
19 is prime
20 is divisible by 2
21 is divisible by 3
22 is divisible by 2
23 is prime
24 is divisible by 2
25 is divisible by 5
26 is divisible by 2
27 is divisible by 3
28 is divisible by 2
29 is prime
30 is divisible by 2
31 is prime
32 is divisible by 2
33 is divisible by 3
34 is divisible by 2
35 is divisible by 5
36 is divisible by 2
37 is prime
38 is divisible by 2
39 is divisible by 3
40 is divisible by 2
41 is prime
42 is divisible by 2
43 is prime
44 is divisible by 2
45 is divisible by 3
46 is divisible by 2
47 is prime
48 is divisible by 2
49 is divisible by 7
50 is divisible by 2
51 is divisible by 3
52 is divisible by 2
53 is prime
54 is divisible by 2
55 is divisible by 5
56 is divisible by 2
57 is divisible by 3
58 is divisible by 2
59 is prime
60 is divisible by 2
61 is prime
62 is divisible by 2
63 is divisible by 3
64 is divisible by 2
65 is divisible by 5
66 is divisible by 2
67 is prime
68 is divisible by 2
69 is divisible by 3
70 is divisible by 2
71 is prime
72 is divisible by 2
73 is prime
74 is divisible by 2
75 is divisible by 3
76 is divisible by 2
77 is divisible by 7
78 is divisible by 2
79 is prime
80 is divisible by 2
81 is divisible by 3
82 is divisible by 2
83 is prime
84 is divisible by 2
85 is divisible by 5
86 is divisible by 2
87 is divisible by 3
88 is divisible by 2
89 is prime
90 is divisible by 2
91 is divisible by 7
92 is divisible by 2
93 is divisible by 3
94 is divisible by 2
95 is divisible by 5
96 is divisible by 2
97 is prime
98 is divisible by 2
99 is divisible by 3
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment