Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python Basics I GIS Applications Spring 2017.

Similar presentations


Presentation on theme: "Python Basics I GIS Applications Spring 2017."— Presentation transcript:

1 Python Basics I GIS Applications Spring 2017

2 Python and ArcGIS Python is tightly integrated into ArcGIS Desktop
Python scripting allows you to create and automate new GIS operations or automate a workflow (e. g. create a map, perform some redundant tasks, perform a complete analysis). import arcpy roads = "c:/base/data.gdb/roads" output = "c:/base/data.gdb/roads_Buffer“ # Run Buffer using the variables set above and pass the remaining # parameters in as strings arcpy.Buffer_analysis(roads, output, "distance", "FULL", "ROUND", "NONE")

3 Python Background Python is an interpreted language – executes instructions directly without compiling into machine language Considered a scripting language - intended to be quick to learn and easy to use. Good for quick prototyping Python is a high level language – it has built in high-level data types, such as arrays and dictionaries, and classes. Has dynamic typing: majority of type checking is performed at run-time as opposed to at compile-time. In dynamic typing, values have types, variables do not.

4 Running Python - the Interpreter
An integrated development environment for Python named IDLE installs with ArcGIS desktop The Integrated DeveLopment Environment (IDLE) provides a default editor, search capabilities and a symbolic debugger. Once Python starts running in interpreter mode, using IDLE or a command shell, it produces a prompt, which waits for your input.

5 Python Variables A variable is a name that refers to a value.
When you create a variable you reserve some space in memory for a value. Based on the data type of the value, the interpreter allocates memory and decides what can be stored in the reserved memory. a=4

6 Python Variables >>> x = 4
Variables are created when a value is assigned to them The equal sign ('=') is used to assign a value to a variable >>> x = 4 Variables must be “defined” (assigned a value) before they can be used, or an error will occur >>> a Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> a NameError: name 'a' is not defined

7 Python Variables Variables do not need to be declared explicitly
Their datatypes are inferred from the assignment statement. Python supports the following data types: Boolean left = True integer x = 10 long y= L float z= 13.33 string name = “George” list mylist=["one", 2, 3.0]

8 Python - Adding comments
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.

9 Python Variables >>> count = #an integer assignment >>> mileage = # a float assignment >>> name ='kate' # a string assignment Use single or double quotation marks to indicate that you are declaring a string variable >>> print name, count, mileage kate Use a print statement to write the results of operations. A value can be assigned to several variables simultaneously: >>>>a=b=c=d=1 >>> print a,b,c,d

10 Python Variables You can assign a number as a string variable by putting it in quotes. >>> mynumber ="4" Then it will behave like a string, not a number. >>> count+mynumber Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> count+mynumber TypeError: unsupported operand type(s) for +: 'int' and 'str'

11 Variable naming Variables in Python follow the standard of an alphanumeric name but must begin with a letter or underscore. Variable names cannot begin with a number. Variable names cannot contain spaces. Variable names are case sensitive. mynumber is a different variable than Mynumber or MyNumber >>>>Mynumber Traceback (most recent call last): File "<pyshell#22>", line 1, in <module> Mynumber NameError: name 'Mynumber' is not defined

12 Variable Naming A recommended practice for Python variables is to name the variable beginning with a lower-case letter, then begin each subsequent word with a capital letter myName, myLastName, roadsTable, bufferField1. Make variable names meaningful so that others can more easily read your code – and it will also help you read your code.

13 Python Reserved Words Variables cannot be any of the special Python reserved words. Python keywords contain lowercase letters only. and exec not assert finally or break for pass class from print continue global raise def if return del import try elif in while else is with except lambda yield

14 Python statements A statement is an instruction that the Python interpreter can execute. A simple statement consists of a single logical line a=1 # an assignment statement b=2 print a # a print statement print b Assignment statements are usually the most common type Assignment statements bind variable names to values An assignment statement produces no output. A print statement produces an output

15 Python - Evaluating expressions
An expression is a combination of values, variables, and operators. Operators are special symbols that represent computations like addition and multiplication. The values the operator uses are called operands. Operators and operands The symbols +, -, and /, and the use of parenthesis for grouping, mean in Python what they mean in mathematics. The asterisk (*) is the symbol for multiplication, and ** is the symbol for exponentiation.

16 Python - Evaluating expressions
When you type an expression on the command line, the interpreter evaluates it and displays the result: >>> Not every expression contains all of these elements. A value all by itself is considered an expression, and so is a variable >>> 324 The left-hand side of an assignment statement has to be a variable name, not an expression >>> a + 1 = b

17 Number Variables Number data types store numeric values.
Python supports four numerical types: int (signed integers) -have at least 32 bits of precision long (long integers - have unlimited precision) float (floating point real values) complex (complex numbers) a = 5 b = L c = 13.33 >>> type(a) <type 'int'> >>> type(b) <type 'long'>

18 Number Operations The Python interpreter acts as a simple calculator.
The operators +, -, * and / work like you would expect x % y remainder of x / y -x x negated abs(x) absolute value of x pow(x, y) x to the power y x ** y >>> a=5 >>> -a -5 >>> abs(a) 5 >>> a**a 3125

19 Number Operations By convention, integer division always rounds down
Binary operations on different numeric types An operand with the “narrower” type is widened to that of the other, Integer is narrower than long integer is narrower than floating point is narrower than complex >>> a =4 >>> b=10 >>> b/a #For integer division, the result is an integer. 2 By convention, integer division always rounds down >>> a=4.0 >>> b/a 2.5

20 Booleans Boolean values are the two constant objects False and True.
They are used to represent truth values (other values can also be considered false or true). >>> a=2 >>> b=3 >>> c=a==b >>> c False >>>

21 Comparison Operations
Meaning < strictly less than <= less than or equal > strictly greater than >= greater than or equal == equal != not equal is object identity is not negated object identity Return True or False >>> a<b True

22 String Variables Strings in Python are identified as a contiguous set of characters in between quotation marks. nameString = “My name is Kate” Python allows for either pairs of single or double quotes. nameString = ‘My name is Kate’ The same type of quote needs to start and end a string. Indexes start at 0 - the beginning of the string Strings are a sequence type and are indexed

23 String Operations Operation Result x in s
True if an item of s is equal to x, else False x not in s False if an item of s is equal to x, else True s + t the concatenation of s and t s * n, n * s n shallow copies of s concatenated s[i] ith item of s, origin 0 s[i:j] slice of s from i to j s[i:j:k] slice of s from i to j with step k len(s) length of s min(s) smallest item of s max(s) largest item of s s.index(x) index of the first occurrence of x in s s.count(x) total number of occurrences of x in s

24 String Operations >>> namestring="My name is Kate"
>>> "M" in namestring # returns a Boolean True >>> "x" in namestring False >>> "x" not in namestring True

25 String Operations Concatenation is done with the + operator.
c = "Computing" i= "Information Science" cis = c+" & " + i >>> cis 'Computing & Information Science' >>> c="Hooray" >>> c *2 'HoorayHooray' s * n, n * s Copies of string concatenated >>> 2*c

26 String Operations len(string): returns the length of a string
8 >>> min(c) 'H' >>> max(c) 'y' Min, max(string): returns first, last character of string >>> c="Hooray"

27 String Operations slice operator ( [ ] and [ : ] )
>>> namestring="My name is Kate" >>> namestring 'My name is Kate' >>> namestring[0] 'M' >>> namestring[2:10] ' name is' >>> namestring[-1] # last character 'e' Indices may also be negative numbers, to start counting from the right: >>> namestring[-2:] # characters from the second-last (included) to the end 'te'

28 String Operations slice operator ( [ ] and [ : ] )
Strings are immutable so namestring[2] = ‘a’ would cause an error Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> namestring[2]=a TypeError: 'str' object does not support item assignment

29 String Operations count operator str.count(sub[, start[, end]])
Returns the number of non-overlapping occurrences of substring sub in the range [start, end]. s="running and jumping" >>> s.count("ing") 2 >>> s2= s+ " and skipping" >>> s2 'running and jumping and skipping' >>> s2.count("ing") 3

30 String Functions Strip -string strip([chars]): returns a copy of the string with leading and tailing characters removed s = " " t=s.strip("0") t '456' By default strip removes all leading and trailing whitespaces in a string. >>> str = " this is string example..."; >>> print str.strip() this is string example...

31 Comparison operations with strings
>>> c= "K" >>> d= "Z" >>> c>d False >>> c==d >>> c<d True Based on alphabetical order

32 Casting Functions int(variable) - casts variable to integer c=10.5
int(c) 10 str(variable) - casts variable to string track = "Track” tracknum =10 track + (str)tracknum float(variable) - casts variable to float float(tracknum) 10.0

33 Some basic syntax rules for Python
Indentation is required in Python to logically group together certain lines, or blocks, of code. The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. if True: print "True" else: print "False"

34 Python - Blank Lines A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it. In an interactive interpreter session, you must enter an empty physical line to terminate a multi-line statement.

35 Python syntax

36 Python syntax Statements on multiple lines need to use a line continuation character, which in Python is a backslash (\). Python then interprets the line sequence as one statement. total = item_one + \ item_two + \ item_three If you use parentheses () or brackets [], Python understands that you are continuing lines and no backslash is required. days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

37 Python syntax The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. import sys; x = 'foo'; sys.stdout.write(x + '\n')

38 Python Modules Modules are code saved in a reuseable form, a script.
They contain Python definitions and statements. By convention, Python script files end with the extension .py. Python has a large collection of standard modules, e.g file I/O, system calls, sockets, and interfaces to graphical user interface toolkits Modules can be imported and reused in other Python programs.

39 Python Modules Importing modules import os, sys, math
>>> from math import sqrt , exp >>> exp( -1) >>> sqrt (2) Module for using Python with ArcGIS import arcpy

40 Commenting your Python code
Add a comment by beginning the line with a pound (#) sign. Comments should explain what the code is doing. Comments are ignored by Python, so you can add them at any place in your code. Comments help others who may have to work with your code in the future; and they may even help you remember what the code does Your scripts should contain a heading section that describes what it does, who created it, and when it was created, along with comments throughout the script itself that explain what it is doing.

41 Commenting your Python code
Single-line comments begin with the hash character ("#") and are terminated by the end of line. Python is ignoring all text that comes after the # to the end of the line, they are not part of the command. Comments spanning more than one line are achieved by inserting a multi-line string (with """ as the delimiter on each end)

42 Commenting your Python code
''' Tool Name: ListFields Source Name: ListFields.py Version: ArcGIS 10.4 Author: Kate Beard Required Arguements: input file Description: prints out the fields and their properties ''' import arcpy #specify an input file feature_class = "c:/old-c/AVdata/FireStations/fire.shp" # Create a list of fields using the ListFields function fields = arcpy.ListFields(feature_class) # Iterate through the list of fields for field in fields: # Print field properties print("Field: {0}".format(field.name))

43 Specifying paths in Python
Paths are stored as string variables. A backslash (\) is a reserved character indicating line continuation or an escape sequence in Python. For instance, \n represents a line feed, \t represents a tab. When specifying a path, a forward slash (/) can be used in place of a backslash. Two backslashes can be used instead of one to avoid a syntax error. Example 1: Valid use of paths in Python fc = "C:/Data/Counties.shp“ Example 2: Invalid use of paths in Python fc= (“C:\temp\streams.shp")


Download ppt "Python Basics I GIS Applications Spring 2017."

Similar presentations


Ads by Google