Python Intro GIS Week 1. Jake K. Carr

Similar documents
Python Review IPRE

Introduction to Python

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Types, lists & functions

Python Review IPRE

Python I. Some material adapted from Upenn cmpe391 slides and other sources

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

Data Structures. Lists, Tuples, Sets, Dictionaries

Python for Non-programmers

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

Python and Bioinformatics. Pierre Parutto

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Python: common syntax

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

>>> * *(25**0.16) *10*(25**0.16)

Programming Fundamentals and Python

At full speed with Python

Here n is a variable name. The value of that variable is 176.

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

Level 3 Computing Year 2 Lecturer: Phil Smith

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

Teaching London Computing

Python - Variable Types. John R. Woodward

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Lists, loops and decisions

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Advanced Python. Executive Summary, Session 1

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

An Introduction to Python

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Chapter 6: List. 6.1 Definition. What we will learn: What you need to know before: Data types Assignments

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Beyond Blocks: Python Session #1

Built-in Types of Data

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

Strings. Genome 373 Genomic Informatics Elhanan Borenstein

Some material adapted from Upenn cmpe391 slides and other sources

ESRI China (Hong Kong) Limited

Intro. Scheme Basics. scm> 5 5. scm>

Statements 2. a operator= b a = a operator b

Python for Non-programmers

Python in 10 (50) minutes

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Algorithms and Programming I. Lecture#12 Spring 2015

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

The Big Python Guide

Strings. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

CSCE 110 Programming I

An Introduction to Python for KS4!

CMSC201 Computer Science I for Majors

Decisions, Decisions. Testing, testing C H A P T E R 7

The Practice of Computing Using PYTHON

Downloaded from Chapter 2. Functions

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

Collections. Lists, Tuples, Sets, Dictionaries

Introduction to Python

IDM 232. Scripting for Interactive Digital Media II. IDM 232: Scripting for IDM II 1

Programming in Python

Introduction to Python, Cplex and Gurobi

Part III Appendices 165

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Exercise: The basics - variables and types

Python. Executive Summary

Variable and Data Type 2

Introduction to Python and programming. Ruth Anderson UW CSE 160 Winter 2017

Sequences: Strings, Lists, and Files

Computer Science 121. Scientific Computing Winter 2016 Chapter 3 Simple Types: Numbers, Text, Booleans

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

COMP 2718: Shell Scripts: Part 1. By: Dr. Andrew Vardy

Python. Karin Lagesen.

CSC148H Week 3. Sadia Sharmin. May 24, /20

Unit E Step-by-Step: Programming with Python

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

CS 115 Lecture 4. More Python; testing software. Neil Moore

PHP. Interactive Web Systems

CSC Software I: Utilities and Internals. Programming in Python

Arithmetic expressions can be typed into Maple using the regular operators:

Lecture 3. Strings, Functions, & Modules

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han

Expressions, Statements, Variables, Assignments, Types

18.1. CS 102 Unit 18. Python. Mark Redekopp

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

CS Advanced Unix Tools & Scripting

Java Bytecode (binary file)

Lists How lists are like strings

ECS15, Lecture 13. Midterm solutions posted. Topic 4: Programming in Python, cont. Staying up to speed with Python RESOURCES. More Python Resources

Transcription:

GIS 5222 Week 1

Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!!

Why Python: Example Consider having to convert 1,000 shapefiles into feature classes in a geodatabase. We could run the appropriate tool (which is?) 1,000 times, but there surely must be a much more efficient and robust way to do this. With Python, we only need a handful of lines of code to carry out this task.

Learning Python: Many, many online sources. See the manual posted to Carmen. General Python: Stavros: http://www.stavros.io/tutorials/python/ Python for ArcGIS: Penn State: https://www.e-education.psu.edu/geog485

Open Python: There are lots of integrated development environments (IDEs) for accessing Python. The default IDE that installs with ArcMap is called IDLE:

Help and Documentation: Python comes with a few built in functions. To see what is available: >>> print dir ( builtins ) There are many basic functions included in base Python: [ abs, dir, help, len, max, min, pow, print, range, reversed, round, slice, sorted, sum ]

Basic Function: abs Consider the basic function abs, which returns the absolute value of the numeric argument passed to it. >>> help ( abs ) Help on built - in function abs in module builtin : abs (...) abs ( number ) -> number Return the absolute value of the argument. Note that help (used above) is also a basic built in function! Using help() tells you what module the function is found in (builtin), as well as the arguments that need to be passed to the function and the output of the function.

Basic Function: dir The basic function dir, which I often forget about, can be useful at times. It returns the attributes associated with an object. >>> help ( dir ) Help on built - in function dir in module builtin : dir (...) dir ([ object ]) -> list of strings The attributes associated with an object probably means nothing to you now, but it will in a bit.

Basic Function: range The basic function range creates a list of indices. Used when trying to enumerate a set of objects. >>> help ( range ) Help on built - in function range in module builtin : range (...) range ([ start,] stop [, step ]) -> list of integers Any function argument enclosed in brackets - like [start,] - indicates that that argument is optional. Arguments that are not enclosed in brackets - like stop - are required.

Basic Function: range Here we create 3 different lists of indices using the range function. How do these lists differ? >>> rangelist = range (2,11,4) >>> print rangelist [2, 6, 10] >>> rangelist2 = range (2,11) >>> print rangelist2 [2, 3, 4, 5, 6, 7, 8, 9, 10] >>> rangelist3 = range (11) >>> print rangelist3 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] What happened in rangelist2 and rangelist3? Python counts numbers from 0 on, unlike humans, which tend to count from 1 on.

Object Assignment Python is an Object Oriented Programming (OOP) language. As we saw above, we assign things to objects. We have already assigned things to the objects called rangelist, rangelist2, and rangelist3. Object names have to follow specific guidelines - they can consist of letters, numbers, & underscores, but they cannot begin with a number: OK: range 2 to 11 Not OK: 2 range 11

Object Assignment Cannot use designated keywords as object names. Note that keywords are highlighted in IDLE. For example, we can t use print or import as an object name. Don t give an object the same name as a function! Python in general is CASE sensitive! >>> Rangelist = range (11) >>> print Rangelist [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> rangelist = range (12) >>> print rangelist [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] >>> Rangelist == rangelist False Rangelist is not the same object as rangelist.

Object Assignment Assignments are modifiable: >>> myvar = 3 >>> print myvar 3 >>> myvar += 2 >>> print myvar 5 >>> myvar -=1 >>> print myvar 4 We ll refer to (+=) or (-=) as a Modify & Assign Operation.

Object Assignment We can make multiple assignments in one line!! >>> var1, var2 = 4, 34 >>> print var1 4 >>> print var2 34 We can even swap assignments in one line!!! >>> var1, var2 = var2, var1 >>> print var1 34 >>> print var2 4

String Objects So far, we have only assigned numbers to Python objects. Sometimes we will want to assign words to an object. Words are called character strings (or just strings) in programming talk and are contained in quote marks (single or double). >>> mystring = " Hello " >>> print mystring Hello String objects are also modifiable: >>> mystring += " world." >>> print mystring Hello world.

More Strings Strings are enclosed in either single quotes or double quotes. If you open a string in single (double) quotes you need to end it in single (double) quotes. >>> string = I like turtles SyntaxError : invalid syntax >>> string = " He said hello " >>> print string He said hello >>> string = He said hello >>> print string He said hello

More Strings A quote in a string has to be placed inside a set of quotes using the opposite punctuation than that used to open/close the string >>> string = " He said hello " >>> print string He said hello >>> badstring = " He said " hello "" SyntaxError : invalid syntax

Data Types Python objects can contain more than one piece of information (or one piece of data). There are three types of Python object for storing data: lists, tuples and dictionaries. A list is just a list of objects, which can be modified. A tuple is a list of objects that can t be modified (so they are more efficient then lists). A dictionary is a list of objects in which each object is given an identifier. Lists are created with square brackets [], tuples with parentheses (), and dictionaries are created with curly brackets {}.

Lists A modifiable list of items (objects). >>> mylist = [1, 2, 3.14] >>> print mylist [1, 2, 3.14] >>> type ( mylist ) <type list > The items don t have to be the same type (numbers and strings): >>> mylist = [" item_1 ", 2, 3.14] >>> print mylist [ item_1, 2, 3.14] >>> type ( mylist ) <type list >

Lists We can even have a list of lists: >>> mylist = [1, [" another ", " list "], ("a", " tuple ")] >>> print mylist [1, [ another, list ], ( a, tuple )] >>> type ( mylist ) <type list >

Indexing List Items We can access or modify items in a list using its index. Index is just a word that means position in the list. Recall that Python starts counting at 0, therefore indexes begin with 0 - not 1. >>> mylist = [1, [" another ", " list "], ("a", " tuple ")] >>> mylist [0] 1 >>> mylist [1] [ another, list ]

Indexing List Items We can replace an item in a list using an indexed assignment: >>> mylist = [1, [" another ", " list "], ("a", " tuple ")] >>> mylist [0] = 4 >>> print mylist [4, [ another, list ], ( a, tuple )] >>> mylist [ -1] = 3.21 >>> print mylist [4, [ another, list ], 3.21] Notice that a negative index (fifth line) tells Python to start from the back of the list.

Dictionaries A dictionary is a list of items (called values ) which are identified by a key. The values are indexed by the key it is associated with - not the index number like with lists. >>> mydict = {" Key_1 ": " Value_1 ", 2: 3, "pi": 3.14} >>> print mydict { Key_1 : Value_1, 2: 3, pi : 3.14} >>> print mydict [ pi ] 3.14 Modifications are assigned with the key as well. >>> mydict [" pi"] = 3.999 >>> print mydict { Key_1 : Value_1, 2: 3, pi : 3.999}

Tuples Tuples are just light-weight lists. You can t modify them. >>> mytuple = (1, 2, 3) >>> print mytuple (1, 2, 3) >>> mytuple [0] 1 >>> mytuple [0] = 4 Traceback ( most recent call last ): File " < pyshell #76 >", line 1, in <module > mytuple [0] = 4 TypeError : tuple object does not support item assignment >>> print mytuple (1, 2, 3)

Other Assignments You can even assign a function to an object! >>> myfunction = len >>> print myfunction ( mytuple ) 3 Here we have assigned the length function to the object called myfunction.

Index Slicing To index over a consectutive set of items we use index slicing, which is accomplished by stating a start position and a read count, seperated by a colon (:). >>> mylist = [" List_item_1 ", 2, 3.14] >>> print mylist [:] [ List_item_1, 2, 3.1400000000000001] >>> print mylist [1:] [2, 3.14] >>> print mylist [0:2] [ List_item_1, 2] >>> print mylist [ -3:1] [ List_item_1 ] If we add a second colon we can specify the step count, so that Python will slice in increments of N instead of 1. >>> print mylist [0:3:2] [ List_item_1, 3.14]

String Slicing String objects can be sliced and diced as well, but there is additional functionality associated with strings that can sometimes be very handy: word reversing. >>> word = abcdef >>> word [:: -1] fedcba >>> word = science >>> word [:: -1] ecneics

More Strings Strings are often useful for creating messages in your code. We can convert numbers into a string object and concatenate the resulting string to other strings. >>> temp = 100 >>> print temp 100 >>> print " The temperature is " + str ( temp ) + " degrees today." The temperature is 100 degrees today.

Concatenating Lists One of the nice features about lists is that they are easily appended - you can add items to a list without re-defining the list. >>> mylist = [" List_item_1 ", 2, 3.14] >>> print mylist [ List_item_1, 2, 3.1400000000000001] >>> mylist + [13] [ List_item_1, 2, 3.1400000000000001, 13] >>> print mylist [ List_item_1, 2, 3.1400000000000001] >>> mylist = mylist + [13] >>> print mylist [ List_item_1, 2, 3.1400000000000001, 13]

Number Types There are two main types of numbers, integer and float. Integers are whole numbers, floats are numbers with decimals. In older versions of Python arithmetic between two integers would result in integer values, so one of the integers would have to be forced into a float type for complete accuracy. >>> 3/1 3 >>> 10/3 3 >>> 10.0/3 3.3333333333333335 >>> 10/3.0 3.3333333333333335

Comparisons In many programming applications we need to compare two (or more) values and then execute a command depending on the comparison. The result of a comparison is either True or False: >>> a = 21 >>> b = 10 >>> a == b False >>> a!= b True

Comparisons We can even make comparisons with items in a list: >>> mylist = [ List_item_1, 2, 3.14] >>> 4 in mylist False >>> 2 in mylist True