PYTHON PROGRAMMING WHAT IS PYTHON Python is a

  • Slides: 28
Download presentation
PYTHON PROGRAMMING

PYTHON PROGRAMMING

WHAT IS PYTHON? § Python is a high-level language. § Interpreted § Object oriented

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

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! §

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 (Arc. Py) § Many open source GIS resources (APIs) 4

VARIABLE § How to name variables? § Meaningful: document what the variables are used

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

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

STRING MANIPULATION § slice out a sub-string from a string Index value string [a : b] Start Include d End Exclude d s = ‘Hello’ part = s[1 : 4] part ‘ell’

STRINGS ARE IMMUTABLE! § A string’s contents can NOT be modified § Not working

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!" new. Greeting = ‟J‟ + greeting[1: ] #create a new one

WHAT IS A LIST? § A list is a sequence of values. § A

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

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’,

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

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! Type. Error: object doesn’t support item assignment

ACCESS TUPLE ELEMENT § Very similar to how you access list elements. >>> tuple

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

WHAT IS A DICTIONARY? § A dictionary is a list of key : value pairs eng 2 sp = {'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 >>> print eng 2 sp unpredictable. {'one': 'uno', 'three': 'tres', 'two': 'dos'}

CREATE A DICTIONARY create a dictionary by providing a list of key-value pairs >>>

CREATE A DICTIONARY create a dictionary by providing a list of key-value pairs >>> eng 2 sp = {‟one‟: ‟uno‟, ‟two‟: ‟dos‟, ‟three‟: ‟tres‟} >>> print eng 2 sp {‟one‟: ‟uno‟, ‟three‟: ‟tres‟, ‟two‟: ‟dos‟} >>> print eng 2 sp[‟two‟] ‟dos‟ >>> dic = {1: ”one”, 2: ”two”, 1: ”uno”} # How does Python deal with it?

DICTIONARY OPERATIONS § Create a dictionary called inventory = {'apples': 430, 'bananas': 312, 'oranges':

DICTIONARY OPERATIONS § Create a dictionary called 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

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 or equal to less than or equal to

LOGICAL OPERATORS § Logical operators are often used in building Boolean expressions. § Three

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 True Result False 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

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

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”: function. A() elif choice == “B”: function. B() elif choice

if choice == “A”: function. A() elif choice == “B”: function. B() elif choice == “C”: function. C() else: print "Invalid choice. " Flowchart of this alternative execution choice==‘A’ True function. A() False choice==‘B’ True function. B() False choice==‘C’ True False function. C() print “Invalid choice”

DEFINING FUNCTIONS Syntax: Indentation for the body of a function: def NAME (LIST OF

DEFINING FUNCTIONS Syntax: Indentation for the body of a function: def NAME (LIST OF PARAMETERS): STATEMENTS Example: Function definition: Function call # function definition def print. Info(): print 'Python version is 2. 7!' # Call function print. Info()

THE RETURN STATEMENT import math def print. Logarithm(x): if x <= 0: print “The

THE RETURN STATEMENT import math def print. Logarithm(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) #log 10 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

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

THE WHILE STATEMENT § Computers are often used to automate repetitive tasks. § Python provides statements (for and while) to achieve • iteration. Evaluate the condition, yielding True or Step 1 False • If the condition is false, exit the statement Step and continue execution at the next statement. 2 • If the condition is true, execute the body and Step then go back to step 1. 3

FOR LOOP § for loops are used when you have a piece of code

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 AN EXISTING TEXT FILE § Like how you read a file: open () read () close() str. Folder. Path = 'd: \Intro 2 Python\Files\' str. File. Name = ‘Read. Me. txt' str. Full. Path = str. Folder. Path + str. File. Name f 2 = open(str. Full. Path, 'r') str = f 2. read() # read the whole file f 2. close() print str Output Clark University is in Worcester is in Massachusetts. Read-only Mode

WRITE A NEW TEXT FILE § Like how you write a file: open ()

WRITE A NEW TEXT FILE § Like how you write a file: open () write () close() str. Folder. Path = 'd: \Intro 2 Python\Fall 2012\Files\' str. File. Name = ‘New. File. txt' str. Full. Path = str. Folder. Path + str. File. Name f=open(str. Path. Name, '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()