PYTHON
PYTHON
PYTHON
RA1711003030394
CSE - G
1
Introduction to Python
Python is a high-level programming language
Open source and community driven
“Batteries Included”
a standard distribution includes many modules
Dynamic typed
Source can be compiled or run just-in-time
Similar to perl, tcl, ruby
2
Why Python?
Unlike AML and Avenue, there is a considerable base
of developers already using the language
“Tried and true” language that has been in
development since 1991
Can interface with the Component Object Model
(COM) used by Windows
Can interface with Open Source GIS toolsets
3
Example Python
Hello World
print “hello world”
Prints hello world to
standard out
Open IDLE and try it out
yourself
Follow along using IDLE
4
String Methods
Assign a string to a
variable
In this case “hw”
hw.title()
hw.upper()
hw.isdigit()
hw.islower()
5
Lists
Think of a list as a stack of cards, on which your
information is written
The information stays in the order you place it in until
you modify that order
Methods return a string or subset of the list or modify
the list to add or remove components
Written as var[index], index refers to order within set
(think card number, starting at 0)
You can step through lists as part of a loop
6
Conditional Branching
if and else
if variable == condition:
#do something based on v == c
else:
#do something based on v != c
elif allows for additional branching
if condition:
elif another condition:
…
else: #none of the above
7
Looping with For
For allows you to loop over a block of code a set
number of times
For is great for manipulating lists:
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)
Results:
cat 3
window 6
defenestrate 12
8
Looping with For
We could use a for loop to perform geoprocessing tasks
on each layer in a list
We could get a list of features in a feature class and
loop over each, checking attributes
Anything in a sequence or list can be used in a For loop
Just be sure not to modify the list while looping
9
Files
Files are manipulated by creating a file object
f = open("points.txt", "r")
The file object then has new methods
print f.readline() # prints line from file
Files can be accessed to read or write
f = open("output.txt", "w")
f.write("Important Output!")
Files are iterable objects, like lists
10
What Is a Program?
Usually, one or more algorithms written in a
programming language that can be translated to run
on a real machine
A name – identifier
Float:
This type is for numbers with possible fraction
parts. Examples: 23.0, -14.561
Integer operators
The operations for integers are:
+ for addition
- for subtraction
* for multiplication
/ for integer division
Example - Fahrenheit to Centigrade
We want to convert a Fahrenheit temperature to
Centigrade.
23