Presentation is loading. Please wait.

Presentation is loading. Please wait.

PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.

Similar presentations


Presentation on theme: "PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library."— Presentation transcript:

1 PYTHON PROGRAMMING

2 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)

3 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

4 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

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

6 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! fruit = "apple" letter_1 = fruit[0] letter_5 = fruit[4] print letter_1 print letter_5 >>> a >>> e

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

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

9 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.

10 CREATE A LIST  The simplest way to create a list is to enclose the elements in a pair of square brackets []:  A list can be heterogeneous ["hello", 2.0, 5, [10, 20]]  Yes, empty lists [] are allowed. Nested cities= [“Boston", “Worcester"] numbers = [17, 123] empty = []

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

12 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

13 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’)

14 WHAT IS A DICTIONARY?  A dictionary is a list of key : value pairs  The order of the key-value pairs does not stay the same.  In fact, the order of items in a dictionary is unpredictable. eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'} >>> print eng2sp {'one': 'uno', 'three': 'tres', 'two': 'dos'}

15 CREATE A DICTIONARY create a dictionary by providing a list of k ey-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?

16 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

17 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

18 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 False Examples: >>> x = True >>> y = False >>> z = x and y >>> z False >>> z = x or y >>> z True

19 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' 5 is positive -5 is negative Output in the Interactive Window

20 ALTERNATIVE EXECUTION (IF/ELSE) The if/else structure for alternative execution: if x%2 == 0: print x, "is even." else: print x, "is odd."

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

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

23 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.

24 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)

25 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 Step 2 If the condition is false, exit the statement and continue execution at the next statement. Step 3 If the condition is true, execute the body and then go back to step 1.

26 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

27 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

28 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()


Download ppt "PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library."

Similar presentations


Ads by Google