Download Module III - 0. Fundamentals of Python Programming

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
PYTHON PROGRAMMING
WHAT IS PYTHON?
 Python is a high-level language.
 Interpreted
 Object oriented (use of classes and objects)
 Standard library is large
 Has many useful modules (math, image, GUI, etc)
WHY PYTHON
 Easy to learn
 Excellent for beginners and experts
 Scripting language designed to automate the execution
of tasks.
 Suitable for projects, large or small
 Cross-platform (Windows, Mac OS, Unix)
3
THE BENEFIT TO KNOW PYTHON
 A useful tool for your academic/professional career!
 A very useful complementary tool for other programming
languages (if you know C++, C#, Java already)
 GIS professionals need this tool
 Development with ESRI products (ArcPy)
 Many open source GIS resources (APIs)
4
VARIABLE
 How to name variables?
 Meaningful: document what the variables are used for.
 Must be legal: cannot be reserved words.
 Follow the rules of an identifier
 Start with a letter or underscore
 Case sensitive!!!
DATA TYPES
 An int and a float are simple data types.
 A string (str) is a compound data type, because it
consists of smaller pieces .
 A string is a sequence of characters!
>>>
>>>
>>>
>>>
a
>>>
e
fruit = "apple"
letter_1 = fruit[0]
letter_5 = fruit[4]
print letter_1
print letter_5
STRING MANIPULATION
 slice out a sub-string from a string
Index value
string [a : b]
Start
Included
End
Excluded
s = ‘Hello’
part = s[1 : 4]
part
‘ell’
STRINGS ARE IMMUTABLE!
 A string’s contents can NOT be modified
 Not working by modifying:
greeting = "Hello, world!"
greeting[0] = ‟J‟
# ERROR! Can’t modify it
 It works by creating a new string
greeting = "Hello, world!"
newGreeting = ‟J‟ + greeting[1:]
#create a new one
WHAT IS A LIST?
 A list is a sequence of values.
 A string can be regarded as a sequence of characters.
 The values in a list are called elements (or items).
 The elements are separated by comma (,)
 The elements in a list can be any type.
CREATE A LIST
 The simplest way to create a list is to enclose the elements
in a pair of square brackets []:
cities= [“Boston", “Worcester"]
numbers = [17, 123]
empty = []
 A list can be heterogeneous
["hello", 2.0, 5, [10, 20]]
 Yes, empty lists [] are allowed.
Nested
ACCESSING ELEMENTS
 Elements in a list can be accessed using the index.
Cheeses=[‘Cheddar’, ‘Edam’, ‘Gouda’]
Cheeses [0]  ‘Cheddar’
Cheeses [1]  ‘Edam’
Cheeses [2]  ‘Gouda’
WHAT IS A TUPLE?
 In Python, a tuple is similar to a list except that it is
immutable
 A tuple is defined within a pair of parentheses
>>> tuple = (’a’, ’b’, ’c’, ’d’, ’e’)
>>> tuple[0] = ’A’ # not allowed!
TypeError: object doesn’t support item
assignment
ACCESS TUPLE ELEMENT
 Very similar to how you access list elements.
>>> tuple = (’a’, ’b’, ’c’, ’d’, ’e’)
# get one element
>>> tuple[0]
’a’
# get a subset of a tuple
>>> tuple[1:3]
(’b’, ’c’)
WHAT IS A DICTIONARY?
 A dictionary is a list of key : value pairs
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
 The order of the key-value pairs does not stay the same.
 In fact, the order of items in a dictionary is
unpredictable.
>>> print eng2sp
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
CREATE A DICTIONARY
create a dictionary by providing a list of key-value pairs
>>> eng2sp = {‟one‟: ‟uno‟, ‟two‟: ‟dos‟, ‟three‟: ‟tres‟}
>>> print eng2sp
{‟one‟: ‟uno‟, ‟three‟: ‟tres‟, ‟two‟: ‟dos‟}
>>> print eng2sp[‟two‟]
‟dos‟
>>> dic = {1:”one”, 2:”two”, 1:”uno”}
# How does Python deal with it?
DICTIONARY OPERATIONS
 Create a dictionary called inventory
inventory = {'apples':430, 'bananas': 312, 'oranges': 525, 'pears': 217}
 Print its contents
>>> print inventory
{'pears': 217, 'apples': 430, 'oranges': 525, 'bananas': 312}
 Del the ‘pears’ element
>>> del inventory['pears']
 Check the length
# the len() works for string, list, tuples, and dictionaries
>>> len(inventory)
3
BOOLEAN EXPRESSIONS
 True and False are Boolean values in Python
 An Boolean expression yields either True or False.
 Relational Operators / Comparison Operators are often
used in Boolean expressions:
==
!=
>
>=
<
<=
equal to
not equal to
greater than
greater than or equal to
less than
less than or equal to
LOGICAL OPERATORS
 Logical operators are often used in building Boolean
expressions.
 Three logical operators: and, or, and not
Expression
True and False
True or False
not False
not True
Result
False
True
True
False
Examples:
>>> x = True
>>> y = False
>>> z = x and y
>>> z
False
>>> z = x or y
>>> z
True
CONDITIONAL EXECUTION (IF)
 We often need the ability to check conditions and
change the behavior of the program accordingly.
x = 5
if x>0:
print x, "is positive"
y = -5
if y < 0:
print y, 'is negative'
Output in the Interactive Window
5 is positive
-5 is negative
ALTERNATIVE EXECUTION (IF/ELSE)
The if/else structure for alternative execution:
if x%2 == 0:
print x, "is even."
else:
print x, "is odd."
if choice == “A”:
functionA()
elif choice == “B”:
functionB()
elif choice == “C”:
functionC()
else:
print "Invalid choice."
Flowchart of this alternative execution
choice==‘A’
True
functionA()
False
choice==‘B’
True
functionB()
False
choice==‘C’
True
False
functionC()
print “Invalid choice”
DEFINING FUNCTIONS
Syntax:
Indentation for the
body of a function:
def NAME (LIST OF PARAMETERS):
STATEMENTS
Example:
Function definition:
Function call
# function definition
def printInfo():
print 'Python version is 2.7!'
# Call function
printInfo()
THE RETURN STATEMENT
import math
def printLogarithm(x):
if x <= 0:
print “The input number must be positive."
return
The return statement terminates the
execution of the function immediately
result = math.log(x) #log10 for common logarithm
print "The natural logarithm of", x, "is", result
The return here does NOT really return anything.
FRUITFUL FUNCTIONS
Fruitful functions are those functions that return values.
Example 1:
import math
# circle-area calculation
def calarea(radius):
area = math.pi * radius**2
return area
r=1
print "The area of a circle with a radius of", r, ”is ", calarea(r)
r=2
print "The area of a circle with a radius of", r, ”is ", calarea(r)
r=3
print "The area of a circle with a radius of", r, ”is ", calarea(r)
THE WHILE STATEMENT
 Computers are often used to automate repetitive tasks.
 Python provides statements (for and while) to achieve
iteration.
Step 1
•Evaluate the condition, yielding True or False
•If the condition is false, exit the statement and
Step 2 continue execution at the next statement.
•If the condition is true, execute the body and
Step 3 then go back to step 1.
FOR LOOP
 for loops are used when you have a piece of code which
you want to repeat n times.
for iterating_var in sequence:
statements
Recall the Traversal Example
fruit = “apple"
# use ‘for … in …’ to traverse a string
for char in fruit:
print char
READ AN EXISTING TEXT FILE
 Like how you read a file:
open ()  read ()  close()
strFolderPath = 'd:\\Intro2Python\\Files\\'
strFileName = ‘ReadMe.txt'
strFullPath = strFolderPath + strFileName
f2 = open(strFullPath,'r')
str = f2.read() # read the
whole file
f2.close()
print str
Output
Clark University is in Worcester.
Worcester is in Massachusetts.
Read-only Mode
WRITE A NEW TEXT FILE
 Like how you write a file:
open ()  write ()  close()
strFolderPath = 'd:\\Intro2Python\\Fall2012\\Files\\'
strFileName = ‘NewFile.txt'
strFullPath = strFolderPath + strFileName
f=open(strPathName, 'w')
#’w’ is for ‘writing’ mode.
# if a file with the same name exits,
# its contents are removed.
f.write('Clark University is in Worcester.\n')
f.write('Worcester is in Massachusetts.')
f.close()