Professional Documents
Culture Documents
Session 1: Introduction To Python Programming: Instructor: Twitter: @hellomukama
Session 1: Introduction To Python Programming: Instructor: Twitter: @hellomukama
Introduction to Python
Programming
Instructor:
Twitter: @HelloMukama
Objectives
• Introduction to the Python programming
language
• Write and execute computer code to
automate repetitive tasks
• Retrieve and use data from common
hydrologic data sources
Twitter: @HelloMukama 2
Week1 Schedule
• Day 1
– Introduction to Python
– Key Python coding concepts and conventions
– Introduction to the coding challenge
• Day 2
– Group work on coding challenge
Twitter: @HelloMukama
Why Python?
• Python is generally:
– Comparatively easy to learn
– Freely available
– Cross-platform (Windows, Mac, Linux)
– Widely used – extensive capabilities, documentation,
and support
– Access to advanced math, statistics, and database
functions
– Integrated into ArcGIS and other applications
– Simple, interpreted language – no compilation step
https://www.python.org 4
What is Python?
Twitter: @HelloMukama 5
Python Basics
• To run Python interactively, we will use Idle (the
Python GUI)
– Command line interpreter – evaluates whatever you type
in
– Text editor with syntax highlighting
– Menu commands for changing settings and running files
Twitter: @HelloMukama 6
Idle on Windows
NB: This idle can act as a simple calculator. Try it out yourself!
Simple Arithmetic
A little house keeping…
Python2 takes no parenthesis
Python3 raises errors without parenthesis
Twitter: @HelloMukama 9
String Manipulation
>>>print(‘Python’ +
‘Programming.’)
PythonProgramming.
>>>
Try typing some string expressions
Twitter: @HelloMukama 10
Variables in python
• Variables are names for values
• Created by use – no declaration necessary
>>>planet = ‘Pluto’
variable value
>>>print(planet)
planet ‘Pluto’
Pluto
>>>moon = ‘Charon’ moon ‘Charon’
>>>
Variables cont..
• Variables can be assigned to other variables
>>>p = planet
>>> variable value
planet ‘Pluto’
moon ‘Charon’
p
Variables cont..
• Variables can be assigned to other variables
>>>p = planet
>>>print(p) variable value
Pluto planet ‘Pluto’
>>> moon ‘Charon’
Twitter: @HelloMukama 14
Variables cont..
• In Python, variables are just names
• Variables do not have data types
string
Twitter: @HelloMukama 15
Variables cont..
• In Python, variables are just names
• Variables do not have data types
integer
Twitter: @HelloMukama 16
Variables cont..
• In Python, variables are just names
• Variables do not have data types
>>>planet = ‘Sedna’
>>>
Twitter: @HelloMukama 18
Variables cont..
• You must assign a value to a variable before
using it
>>>planet = ‘Sedna’
>>>print(plant) #Note the deliberate misspelling
Twitter: @HelloMukama 19
Variables cont..
• You must assign a value to a variable before
using it
>>>planet = ‘Sedna’
>>>print(plant) #Note the deliberate misspelling
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
print plant
NameError: name 'plant' is not defined
A traceback is an error in python code.
Unlike some languages – Python does not initialize variables with a default value
20
Values Do Have Types
>>>string = ‘two’
>>>number = 3
>>>print(string * number)
Twitter: @HelloMukama 21
Values Do Have Types
>>>string = ‘two’
>>>number = 3
>>>print(string * number) #Repeated concatenation
>>>twotwotwo
>>>
Twitter: @HelloMukama 22
Values Do Have Types
>>>string = ‘two’
>>>number = 3
>>>print(string * number) #Repeated concatenation
>>>twotwotwo
>>>print(string + number)
>>>
‘two3’ ????
If so, then what is the result of ‘2’ + ‘3’
• Should it be the string ‘23’
• Should it be the number 5
• Should it be the string ‘5’Twitter: @HelloMukama 23
Values Do Have Types
>>>string = ‘two’
>>>number = 3
>>>print(string * number) #Repeated concatenation
twotwotwo
>>>print(string + number)
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
print string + number
TypeError: cannot concatenate 'str' and 'int' objects
Twitter: @HelloMukama 24
Use Functions to Convert Between Types
>>>print(int(‘2’) + 3)
5
>>>
Twitter: @HelloMukama 25
Arithmetic in Python
Addition 35 + 22 57
+
‘Py’ + ‘thon’ ‘Python’
Subtraction 35 - 22 13
-
Multiplication 3*2 6
*
‘Py’ * 2 ‘PyPy’
Twitter: @HelloMukama 26
Comparisons
>>>3 < 5
True
>>> Comparisons turn
numbers or
strings into True
or False
Twitter: @HelloMukama 27
Comparisons
3<5 True Less than
3 != 5 True Not equal to
3 == 5 False Equal to (Notice double ==)
3 >= 5 False Greater than or equal to
1<3<5 True Multiple comparisons
Twitter: @HelloMukama 30
Dictionaries
• A collection of pairs (or items) where each pair
has a key and a value
>>> D = {‘Jeff’: ‘a’, ‘Steve’:‘b’, ‘Jon’:‘c’}
>>> D[‘Jeff’]
‘a’
>>> D[‘Steve’] = ‘d’ #update value for key ‘Steve’
>>> D[‘Steve’]
‘d’
Twitter: @HelloMukama 31
Behold the Power of Programming!
• The real power of programming comes from
the ability to perform:
Twitter: @HelloMukama 32
Selection – if, elif, and else
moons = 3
if moons < 0: Always starts with if and a condition
greater
>>>
Twitter: @HelloMukama 34
Indentation
• Python uses indentation to show which
statements are in an if, elif, else statement
Twitter: @HelloMukama 35
Repetition - Loops
• Simplest form of repetition is the while loop
numMoons = 3
while numMoons > 0:
print(numMoons)
numMoons -= 1
Twitter: @HelloMukama 36
Repetition - Loops
• Simplest form of repetition is the while loop
numMoons = 3
while numMoons > 0: While this is true
print(numMoons)
Do this
numMoons -= 1
Twitter: @HelloMukama 37
Repetition - Loops
>>>numMoons = 3
>>>while numMoons > 0:
print(numMoons)
numMoons -= 1
3
2
1
>>>
Twitter: @HelloMukama 38
Combine Looping and Selection
numMoons = 0
while numMoons < 5:
if numMoons > 0:
print(numMoons)
numMoons += 1
Twitter: @HelloMukama 39
Combine Looping and Selection
>>>numMoons = 0
>>>while numMoons < 5:
if numMoons > 0:
print(numMoons)
numMoons += 1
1
2
3
4
>>>
Twitter: @HelloMukama 40
Saving and Executing Code
• Writing and executing complex code is too
difficult to do line by line at the command line
• As soon as you close the Python interpreter,
all of your work is gone…
• Instead
– Write code using a text editor
– Save the code as a text file with a “.py” extension
– Execute code in the file from the command line
Twitter: @HelloMukama 41
Using a Script File
• Start a new Python text file in Idle. You can write Python in
Notepad, but if you use a formal editor, you get color coding!
• Click “File/New File”. This will open the script editor.
• Write your script and save it as a “*.py” file. Then click
“Run/Run Module” to test it….
Results appear in the “shell”
window.
42
Modules
• You may want to reuse a function that you have
written in multiple scripts without copying the
definition into each one
• Save the function(s) as a module
• Import the module into other scripts
• It’s like an “extension” or “plug-in”
Twitter: @HelloMukama 43
Import a Module into a Script
Twitter: @HelloMukama 44
Some Python Resources
• Python 2.7.8 documentation:
https://docs.python.org/2/index.html
• Software Carpentry: http://software-
carpentry.org/index.html
• Python in Hydrology:
http://www.greenteapress.com/pythonhydro/
pythonhydro.html
Twitter: @HelloMukama 46
Get the Data
http://waterdata.usgs.gov/nwis/uv?cb_00060=on&format=rdb&site_no=10109000&period=&begin_date=201
4-08-18&end_date=2014-08-25 47
Coding Challenge
1. Divide into small groups of no more than 3-4 people
2. Choose a real-time streamflow gage from the USGS
that you are interested in. It could be a nearby gage
or one that is near and dear to your heart. To see an
interactive map of gage locations, go to:
http://maps.waterdata.usgs.gov/mapper/index.html
3. Create a Python script that does the following:
a. Download the most recent data from the USGS website
b. Read the file
c. Extract the most recent streamflow value from the file
d. Print the most recent streamflow value and the date at
which it occurred to the screen
Twitter: @HelloMukama 48
Example Solution
Twitter: @HelloMukama 49
Some Hints
• Develop your solution as a script so you can save it as a
file.
• The USGS website returns the data as a file, but you
have to request it using a URL in your code. The
Python module called “urllib2” is one option for
downloading a file using a URL.
• The data are returned in a text file where each new line
represents a new date/time and data value. The
Python module called “re” is one option for splitting a
string using delimiters such as tabs or new-line
characters.
• Also – check out the Python “split” method
Twitter: @HelloMukama 50
Credits
• Some instructional materials adapted from
the Software Carpentry website
http://software-carpentry.org
Copyright © Software Carpentry
Support:
Twitter: @HelloMukama EPS 1135482 51