Introduction to Python. Python is a high-level programming language Open source and community driven “Batteries Included” – a standard distribution includes.

Slides:



Advertisements
Similar presentations
Intro to Python Welcome to the Wonderful world of GIS programing!
Advertisements

Why python? Automate processes Batch programming Faster Open source Easy recognition of errors Good for data management What is python? Scripting programming.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
What is a scripting language? What is Python?
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
GIS Topics and Applications
Python & ModelBuilder. Overview Python/ModelBuilder Concepts – The Geoprocessor – Checking some environment variables – Providing feedback from your model/script.
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
Spatial Analysis, Geoprocessing,
Scripting Languages CS351 – Programming Paradigms.
Guide To UNIX Using Linux Third Edition
Chapter 11 ASP.NET JavaScript, Third Edition. 2 Objectives Learn about client/server architecture Study server-side scripting Create ASP.NET applications.
ModelBuilder at ArcGIS 9.2 Lyna Wiggins Rutgers University May 2008.
CSC 9010: Natural Language Processing
Python Control of Flow.
Python.
Python Mini-Course University of Oklahoma Department of Psychology Day 1 – Lesson 2 Fundamentals of Programming Languages 4/5/09 Python Mini-Course: Day.
Python Programming Fundamentals
Python & ModelBuilder. Continuing Education Python and ModelBuilder Overview Python/ModelBuilder Concepts –The Geoprocessor –Checking some environment.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 35 – Python Outline 35.1 Introduction First Python Program Python Keywords 35.2 Basic.
Esri International User Conference | San Diego, CA Technical Workshops | Python – Getting Started Drew Flater, Ghislain Prince July 12 - July 14, 2011.
2006 GIS Jam: ArcGIS Python Scripting
Writing Geoprocessing Scripts With ArcGIS Lecture 9.
Introduction to Python John Reiser May 5 th, 2010.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Python: An Introduction
1 Python CIS*2450 Advanced Programming Concepts Material for this lecture was developed by Dr. D. Calvert.
Sorting and Modules. Sorting Lists have a sort method >>> L1 = ["this", "is", "a", "list", "of", "words"] >>> print L1 ['this', 'is', 'a', 'list', 'of',
Introduction to Python September 26, /10/ Bioinformatics Languages Low-level, compiled languages: C, C++, Java… Pros: performance Cons:
Introduction of Geoprocessing Topic 7a 4/10/2007.
Python, Toolboxes, Tools & Script Tools
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
If statements while loop for loop
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Built-in Data Structures in Python An Introduction.
Module 6: Geoprocessing Scripts. Processing loops and decisions.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
5 1 Data Files CGI/Perl Programming By Diane Zak.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Introduction of Geoprocessing Lecture 9. Geoprocessing  Geoprocessing is any GIS operation used to manipulate data. A typical geoprocessing operation.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Introduction of Geoprocessing Lecture 9 3/24/2008.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
Dept. of Animal Breeding and Genetics Programming basics & introduction to PERL Mats Pettersson.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Introduction to GIS PythonScript CGIS-NURIntroduction to ArcGIS II.
Introduction Python is an interpreted, object-oriented and high-level programming language, which is different from a compiled one like C/C++/Java. Its.
PYTHON: AN INTRODUCTION
Engineering Innovation Center
Lecture 9 Using Python for Geoprocessing
CS190/295 Programming in Python for Life Sciences: Lecture 6
I210 review.
Geography 465 GIS Database Programming
Lists Like tuples, but mutable. Formed with brackets: Assignment: >>> a = [1,2,3] Or with a constructor function: a = list(some_other_container) Subscription.
Presentation transcript:

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

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

Why not Visual Basic? Visual Basic is still the method of configuring and customizing ArcMap If you have a button on the toolbar, it’s VB Python scripts can be placed in ArcToolbox Python can be run from the command line without ArcMap or ArcCatalog being open Using just the GIS Engine, lower overhead Rapid prototyping, ease of authoring, etc.

Python Interfaces IDLE – a cross-platform Python development environment IDLE PythonWin – a Windows only interface to Python PythonWin Python Shell – running 'python' from the Command Line opens this interactive shell For the exercises, we'll use IDLE, but you can try them all and pick a favorite

IDLE – Development Environment IDLE helps you program in Python by: – color-coding your program code – debugging – auto-indent – interactive shell

Example Python Hello World print “hello world” Prints hello world to standard out Open IDLE and try it out yourself Follow along using IDLE

More than just printing Python is an object oriented language Practically everything can be treated as an object “hello world” is a string Strings, as objects, have methods that return the result of a function on the stringhave methods

String Methods Assign a string to a variable In this case “ hw ” hw.title() hw.upper() hw.isdigit() hw.islower()

String Methods The string held in your variable remains the same The method returns an altered string Changing the variable requires reassignment – hw = hw.upper() – hw now equals “HELLO WORLD”

Other Python Objects Lists (mutable sets of strings) – var = [] # create list – var = [‘one’, 2, ‘three’, ‘banana’] Tuples (immutable sets) – var = (‘one’, 2, ‘three’, ‘banana’) Dictionaries (associative arrays or ‘hashes’) – var = {} # create dictionary – var = {‘lat’: , ‘lon’: } – var[‘lat’] = Each has its own set of methods

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

List Methods Adding to the List – var[n] = object replaces n with object – var.append(object) adds object to the end of the list Removing from the List – var[n] = [] empties contents of card, but preserves order – var.remove(n) removes card at n – var.pop(n) removes n and returns its value

Lists in ArcToolbox You will create lists: Layers as inputs Attributes to match Arrays of objects You will work with lists: List of field names List of selected features

Tuples Like a list, tuples are iterable arrays of objects Tuples are immutable – once created, unchangeable To add or remove items, you must redeclare Example uses of tuples – County Names – Land Use Codes – Ordered set of functions

Dictionaries Dictionaries are sets of key & value pairs Allows you to identify values by a descriptive name instead of order in a list Keys are unordered unless explicitly sorted Keys are unique: – var[‘item’] = “apple” – var[‘item’] = “banana” – print var[‘item’] prints just banana

Indentation and Blocks Python uses whitespace and indents to denote blocks of code Lines of code that begin a block end in a colon: Lines within the code block are indented at the same level To end a code block, remove the indentation You'll want blocks of code that run only when certain conditions are met

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

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

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

Modules Modules are additional pieces of code that further extend Python’s functionality A module typically has a specific function – additional math functions, databases, network… Python comes with many useful modules arcgisscripting is the module we will use to load ArcGIS toolbox functions into Python

Modules Modules are accessed using import – import sys, os # imports two modules Modules can have subsets of functions – os.path is a subset within os Modules are then addressed by modulename.function() – sys.argv # list of arguments – filename = os.path.splitext("points.txt") – filename[1] # equals ".txt"

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

Error Capture Check for type assignment errors, items not in a list, etc. Try & Except try: a block of code that might have an error except: code to execute if an error occurs in "try" Allows for graceful failure – important in ArcGIS

Additional Python Resources Python Homepage Dive Into Python Learning Python, 3 rd Edition Getting Started Writing Geoprocessing Scripts Available on ESRI's support page Available on ESRI's support page