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

Similar documents
GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

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

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

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Babu Madhav Institute of Information Technology, UTU 2015

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

Key Differences Between Python and Java

Introduction to Programming Using Java (98-388)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Introduction to Python

Part III Appendices 165

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

Introduction to Python for Plone developers

Table of Contents EVALUATION COPY

Glossary. For Introduction to Programming Using Python By Y. Daniel Liang

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

egrapher Language Reference Manual

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

ENGR 102 Engineering Lab I - Computation

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

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

Coral Programming Language Reference Manual

PYTHON CONTENT NOTE: Almost every task is explained with an example

Java Bytecode (binary file)

Java+- Language Reference Manual

Python. Objects. Geog 271 Geographic Data Analysis Fall 2010

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Absolute C++ Walter Savitch

Python in 10 (50) minutes

Table of Contents. Preface... xxi

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

CS Summer 2013

And Parallelism. Parallelism in Prolog. OR Parallelism

Introduction to Programming in Python (1)

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Control Structures. CIS 118 Intro to LINUX

Beyond Blocks: Python Session #1

JME Language Reference Manual

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

What Version Number to Install

BoredGames Language Reference Manual A Language for Board Games. Brandon Kessler (bpk2107) and Kristen Wise (kew2132)

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Basic Python 3 Programming (Theory & Practical)

Python Intro GIS Week 1. Jake K. Carr

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

XQ: An XML Query Language Language Reference Manual

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

[CHAPTER] 1 INTRODUCTION 1

Python: common syntax

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like

Review. Input, Processing and Output. Review. Review. Designing a Program. Typical Software Development cycle. Bonita Sharif

Spoke. Language Reference Manual* CS4118 PROGRAMMING LANGUAGES AND TRANSLATORS. William Yang Wang, Chia-che Tsai, Zhou Yu, Xin Chen 2010/11/03

2 nd Week Lecture Notes

COMS W4115 Programming Languages & Translators GIRAPHE. Language Reference Manual

Play with Python: An intro to Data Science

IT 374 C# and Applications/ IT695 C# Data Structures

VLC : Language Reference Manual

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

The Big Python Guide

Index COPYRIGHTED MATERIAL

Data Structures (list, dictionary, tuples, sets, strings)

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

FRAC: Language Reference Manual

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

APT Session 2: Python

The Pyth Language. Administrivia

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Accelerating Information Technology Innovation

Control Structures 1 / 17

Python Evaluation Rules

Course Outline - COMP150. Lectures and Labs

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department

Course Title: Python + Django for Web Application

Overview of List Syntax

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

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

Begin to code with Python Obtaining MTA qualification expanded notes

ARG! Language Reference Manual

CS201 Some Important Definitions

Python INTRODUCTION: Understanding the Open source Installation of python in Linux/windows. Understanding Interpreters * ipython.

OBJECT ORIENTED PROGRAMMING

4. Inputting data or messages to a function is called passing data to the function.

QUark Language Reference Manual

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

AI Programming CS S-02 Python

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

DaMPL. Language Reference Manual. Henrique Grando

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

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

Overview of the Ruby Language. By Ron Haley

DAVE. Language Reference Manual. Hyun Seung Hong. October 26, 2015

Python Review IPRE

CS 231 Data Structures and Algorithms, Fall 2016

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

TUPLES AND RECURSIVE LISTS 5

Transcription:

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

Statement Syntax

The if-elif-else statement Indentation and and colons are important Parentheses and semicolons are optional Do not need to use elif or else if you don t need it

Level of indentation, Pass, += Level of indentation is important Empty blocks are not allowed, so use pass += appends to the string

Pass on nested indentations Better to rewrite earlier code to avoid nesting or the use of pass

and or not With x = 3 and y = 4 Also: (why?)

Assignments Multiple assignment: Can assign the same value to multiple variables:

Ternary assignment Can be a little cryptic

Initialize variables before use Variables have to be initialized before they are used Bad (why?) Variables take global scope

Assignment-based idioms Swapping and sequence assignment Slicing:

Caveat: Shared references What is happening here? Why?

Primitives vs. Objects Python distinguishes between primitives which are directly stored on the hardware and objects which are composed of primitives and are a software construct Primitives get their own piece of the hardware, and so: 5 5 17 5 Whereas object variables are just references to memory 0xa4 0xfe 0xa4 0xfe? What is in the list? Is it the characters hello or a reference to the list of chars?

Clones You can avoid this problem by using copies of the objects However, shared references is usually what you want

Find out Is a string a primitive or is it an object? How could you verify? Try it out (use list and primitive examples earlier) Here are some available operations on a String

Strings are immutable Strings are objects, but they behave like primitives Have no methods to alter them in-place

print without a newline Use a comma:

A while loop

Python Types

Integers and floating point Basic numeric types in Python: Integers Floating point numbers Base-8, base-16 numbers, etc. Normally, you can go with Python s default types but

Floor division // is called a floor operation: Works regardless of operand type (integer or float)

Math operations Import the math library Commonly, you may also see:

Decimals Can avoid problems with rounding and precision by using decimal

Fractions

Fractions from floats

Sets have unique entries

Set comprehension

String is an object and has methods

Raw strings Can escape a string with backslashes Or use the raw string format Can use either single quote or double quote

Multi-line strings Can use multi-line strings as a way to comment out multiple lines of code

Lists

Sorting keys, order

Custom comparator Just define a function and use it to sort

A dictionary is an associative array

Dynamically building dictionary

Tuples work like immutable lists Use tuples if you want data integrity Use lists otherwise

Writing Files Files are first-class types in Python Unlike print(), write() does not automatically add a new line

Reading files Can read an entire file as a string Can get the lines by splitting:

Reading line-by-line Can iterate through a file line-by-line Can manually iterate through a file using next()

Iterating through lists, tuples, maps Using a for-loop: For manual iteration, you need to first create an iter File objects act as their own iterator, so this step was not needed

Saving objects To save objects, use the pickle module

Reading pickled objects

Functions

Why functions? Functions allow you to: Create reusable code Break down complex logic into easily understood pieces

Example function The def keyword creates a function object Note the Python documentation The return statement ends the function call and sends result back to caller A function without a return statement returns None

def is evaluated at runtime Can embed def inside an if statement or inside a function

Aliasing functions Simply assign to a new name And call function using that new name

Function arguments are typeless The arguments get their types at runtime As if code is reinterpreted by Python compiler each time

Variable scope is lexical

Four ways of calling a function Given this function: Can call it by position or by argument name Can use sequence to represent positions Can use dictionary to represent argument names

Modules

Using modules Fetch a module as a whole using import Fetch particular names from a module using from

Module search path Modules are searched for in this order: The home directory of the program If you call import from a.py, it looks in the same directory as a.py In interactive mode, it is the directory in which IDLE was started The environment variable PYTHONPATH Python install directories A search path specified in a.pth file by person installing software

Imports happen only once Imports happen only once Use reload in interactive sessions Can also use this to change some code and re-read it

Package imports A statement such as: Imports the file haversine.py from the directory sp\ch00 Relative to somewhere on the module search path The directories themselves have to a file named init.py Relative paths (. and..) do not work in 2.7 (only 3.0)

Test methods To write code that runs only when a module is run as a main program, but not when it is imported, you can do: This is a convenient way to test functions

Classes and objects

Object = way of grouping fields Often convenient to group data values together Define such groups in a class Provide an initialization function (called a constructor) To use this object, you have to first create it:

Object = fields + methods Can define methods on an object which operates on fields Think of methods as being called on an object:

Testing objects Often useful to test objects by putting usage code in module But would like to prevent test code when running module Use the name construct as follows:

Inheritance Can add extra data to an object by inheriting it: Point3D has all the fields and methods of Point And has an extra ht field and an extra getheight() method

Over-riding methods Can override methods to take advantage of new information

Operator overloading The init method is an example of operator overloading Can optionally implement the following methods: add What happens when someone does a + b? Also: sub, gt, lt, le, ge str What happens when someone does print(a)? del What happens when object is garbage collected (reclaimed)

Exceptions

What are exceptions? Exceptions are errors that make the rest of the code pointless Think of it as a go to that goes back to whoever called the code

Catching exceptions Put the code that could throw the exception in a try Catch it in an except

Practice: Data Analysis of Text Files We will work with a dataset of major cities from: http://www.mongabay.com/cities_pop_01.htm Select the top 20 or so cities from the list Copy-and-paste into a.txt document The data should come in as separate lines with the fields on each line separated by tabs Goal: Find the top 5 most dense cities Density = population / area Also print out the city with the minimum density

Solution: practice

Solution: practice

Homework Read iow_firehydrants.txt Contains the locations of fire hydrants in Isle of Wight, North Carolina For each hydrant, compute the distance of the hydrant nearest to it (this will be the backup hydrant if this hydrant were not available) Print 5 most indispensable hydrants (there is nothing else close by)