Lecture 12 Programming for automation of common data management tasks

Size: px
Start display at page:

Download "Lecture 12 Programming for automation of common data management tasks"

Transcription

1 Lecture 12 Programming for automation of common data management tasks Daniel P. Ames Hydroinformatics Fall 2012 This work was funded by National Science Foundation Grant EPS

2 Goals this Week To learn the basics of Python Scripting for automation of basic geoprocessing and database management tasks. Tuesday focus on intro to Python and ArcPy for mapping and geoprocessing tasks Thursday focus on PyODBC and using Python to automate database tasks

3 Useful Software to have on your laptop computer in class ArcGIS. Python. PyODBC. ArcMap 10.x comes with Python 2.6. It installs it in your C: folder under C:\Python\ArcGIS10\. PyODBC. ads/detail?name=pyodbc win32- py2.6.exe&can=2&q=

4 Slide Credits 2010 Mitch Marcus and Varun Aggarwala, University of Pennsylvania 2010 ESRI Conference Workshop: Python Essentials in ArcGIS-I 2002 LinuxWorld Tutorial: Introduction to Python by Guido van Rossum

5 Python Python is an open source scripting language. Developed by Guido van Rossum in the early 1990s Named after Monty Python Available on eniac Available for download from CIS Intro to NLP 5

6

7 Why Python? Powerful but unobtrusive object system Every value is an object Classes guide but do not dominate object construction Powerful collection and iteration abstractions Dynamic typing makes generics easy

8 Python Interpreted language: works with an evaluator for language expressions Dynamically typed: variables do not have a predefined type Rich, built-in collection types: Lists Tuples Dictionaries (maps) Sets Concise

9 Language features Indentation instead of braces Newline separates statements Several sequence types Strings : made of characters, immutable Lists [ ]: made of anything, mutable Tuples ( ) : made of anything, immutable Powerful subscripting (slicing) Functions are independent entities (not all functions are methods) Exceptions

10 Basics

11 Dynamic typing Variables come into existence when first assigned a value A variable can refer to an object of any type

12 Playing with Python (1) >>> >>> 2/3 0 >>> 2.0/ >>> x=4.5 >>> int(x) 4

13 Playing with Python (2) >>> x='abc' >>> x[0] 'a' >>> x[1:3] 'bc' >>> x[:2] 'ab >>> x[1]='d' Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> x[1]='d' TypeError: 'str' object does not support item assignment

14 Playing with Python (3) >>> x=['a','b','c'] >>> x[1] 'b' >>> x[1:] ['b', 'c'] >>> x[1]='d' >>> x ['a', 'd', 'c']

15 Playing with Python (4) >>> def p(x): if len(x) < 2: return True else: return x[0] == x[-1] and p(x[1:-1]) >>> p('abc') False >>> p('aba') True >>> p([1,2,3]) False >>> p([1, a, a,1]) True >>> p((false,2,2,false)) True >>> p(( a,1,1)) False

16 The Python Command Line Interpreter Interactive interface to Python % python Python 2.6 (r26:66714, Feb , 20:49:49) [GCC [gcc-4_3-branch revision ]] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> Python interpreter evaluates inputs: >>> 3*(7+2) 27

17 The IDLE GUI Environment (Windows) Shell for interactive evaluation. Text editor with color-coding and smart indenting for creating Python files. Menu commands for changing system settings and running files. Installed with ArcMap

18 A Code Sample (in IDLE) x = # A comment. y = Hello # Another one. z = 3.45 if z == 3.45 or y == Hello : x = x + 1 y = y + World # String concat. print x print y

19 Enough to Understand the Code Indentation matters to the meaning of the code: Block structure indicated by indentation The first assignment to a variable creates it. Variable types don t need to be declared. Python figures out the variable types on its own. Assignment uses = and comparison uses ==. For numbers + - * / % are as expected. Special use of + for string concatenation. Special use of % for string formatting (as with printf in C) Logical operators are words (and, or, not) not symbols Simple printing can be done with print.

20 Basic Datatypes Integers (default for numbers) z = 5 / 2 Floats # Answer is 2, integer division. x = Strings Can use or to specify. abc abc (Same thing.) Unmatched can occur within the string. matt s Use triple double-quotes for multi-line strings or strings than contain both and inside of them: a b c

21 Whitespace Whitespace is meaningful in Python: especially indentation and placement of newlines. Use a newline to end a line of code. Use \ when must go to next line prematurely. No braces { } to mark blocks of code in Python Use consistent indentation instead. The first line with less indentation is outside of the block. The first line with more indentation starts a nested block Often a colon appears at the start of a new block. (E.g. for function and class definitions.)

22 Comments Start comments with # the rest of line is ignored. Can include a documentation string as the first line of any new function or class that you define. The development environment, debugger, and other tools use it: it s good style to include one. def my_function(x, y): This is the docstring. This function does blah blah blah. # The code would go here...

23 Naming Rules Names are case sensitive and cannot start with a number. They can contain letters, numbers, and underscores. bob Bob _bob _2_bob_ bob_2 BoB There are some reserved words: and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while

24 The + Operator The + operator produces a new tuple, list, or string whose value is the concatenation of its arguments. >>> (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) >>> [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] >>> Hello + + World Hello World

25 Lists >>> li = [ abc, 23, 4.34, 23] >>> li[1] = 45 >>> li [ abc, 45, 4.34, 23] We can change lists in place. Name li still points to the same memory reference when we re done.

26 Operations on Lists Only 1 >>> li = [1, 11, 3, 4, 5] >>> li.append( a ) # Note the method syntax >>> li [1, 11, 3, 4, 5, a ] >>> li.insert(2, i ) >>>li [1, 11, i, 3, 4, 5, a ]

27 Functions

28 Defining Functions Function definition begins with def Function name and its arguments. def get_final_answer(filename): Documentation String line1 line2 return total_counter Colon. The indentation matters First line with less indentation is considered to be The keyword return indicates the outside of the function definition. value to be sent back to the caller. No header file or declaration of types of function or arguments. CIS Intro to NLP

29 Python and Types Python determines the data types of variable bindings in a program automatically. Dynamic Typing But Python s not casual about types, it enforces the types of objects. Strong Typing So, for example, you can t just append an integer to a string. You must first convert the integer to a string itself. x = the answer is # Decides x is bound to a string. y = 23 print x + y # Decides y is bound to an integer. # Python will complain about this.

30 Calling a Function The syntax for a function call is: >>> def myfun(x, y): return x * y >>> myfun(3, 4) 12

31 Functions without returns All functions in Python have a return value even if no return line inside the code. Functions without a return return the special value None. None is a special constant in the language. None is used like NULL, void, or nil in other languages. None is also logically equivalent to False. The interpreter doesn t print None

32 Logical Expressions

33 True and False True and False are constants in Python. Other values equivalent to True and False: False: zero, None, empty container or object True: non-zero numbers, non-empty objects Comparison operators: ==,!=, <, <=, etc. X and Y have same value: X == Y Compare with X is Y : X and Y are two variables that refer to the identical same object.

34 Boolean Logic Expressions You can also combine Boolean expressions. True if a is True and b is True: a and b True if a is True or b is True: True if a is False: a or b not a Use parentheses as needed to disambiguate complex Boolean expressions.

35 Special Properties of and and or Actually and and or don t return True or False. They return the value of one of their sub-expressions (which may be a non-boolean value). X and Y and Z If all are true, returns value of Z. Otherwise, returns value of first false sub-expression. X or Y or Z If all are false, returns value of Z. Otherwise, returns value of first true sub-expression. And and or use lazy evaluation, so no further expressions are evaluated

36 Control of Flow

37 if Statements if x == 3: print X equals 3. elif x == 2: print X equals 2. else: print X equals something else. print This is outside the if. Be careful! The keyword if is also used in the syntax of filtered list comprehensions. Note: Use of indentation for blocks Colon (:) after boolean expression

38 while Loops >>> x = 3 >>> while x < 5: print x, "still in the loop" x = x still in the loop 4 still in the loop >>> x = 6 >>> while x < 5: print x, "still in the loop" >>>

39 For Loops

40 For Loops 1 For-each is Python s only for construction A for loop steps through each of the items in a collection type, or any other type of object which is iterable for <item> in <collection>: <statements> If <collection> is a list or a tuple, then the loop steps through each element of the sequence. If <collection> is a string, then the loop steps through each character of the string. for somechar in Hello World : print somechar

41 For Loops 2 for <item> in <collection>: <statements> <item> can be more complex than a single variable name. When the elements of <collection> are themselves sequences, then <item> can match the structure of the elements. This multiple assignment can make it easier to access the individual parts of each element. for (x, y) in [(a,1), (b,2), (c,3), (d,4)]: print x

42 String Operations A number of methods for the string class perform useful formatting operations: >>> hello.upper() HELLO Check the Python documentation for many other handy string operations. Helpful hint: use <string>.strip() to strip off final newlines from lines read from files

43 Importing and Modules

44 Importing and Modules Use classes & functions defined in another file. A Python module is a single file with the same name (plus the.py extension) Where does Python look for module files? The list of directories where Python looks: sys.path To add a directory of your own to this list, append it to this list. sys.path.append( /my/new/path )

45 Commonly Used Modules Some useful modules to import, included with Python: Module: sys Maxint Module: os Module: os.path - Lots of handy stuff. - OS specific code. - Directory processing.

46 More Commonly Used Modules Module: math Exponents sqrt - Mathematical code. Module: Random - Random number code. Randrange Uniform Choice Shuffle To see what s in the standard library of modules, check out the Python Library Reference: Or O Reilly s Python in a Nutshell: (URL works inside of UPenn, afaik, otherwise see the course web page)

47 Finally pass It does absolutely nothing. Just holds the place of where something should go syntactically. Programmers like to use it to waste time in some code, or to hold the place where they would like put some real code at a later time. for i in range(1000): pass

48 ArcPy Python Scripting Basics

49 Why use Python scripting in ArcMap? Python: a free, cross-platform, and easy to learn language Used to execute single tools or strings of tools Develop, execute, and share geoprocessing workflows Automation

50 ArcPy The access point to every geoprocessing tool A package of functions, classes and modules, all related to scripting in ArcGIS - Functions that enhance geoprocessing workflows (ListFeatureClasses, Describe, SearchCursor ) - Classes that can be used to create complex objects (SpatialReference and FieldMap objects) - Modules that provide additional functionality (Mapping and SpatialAnalyst modules) Builds on arcgisscripting module (pre-10.0)

51 ArcGIS Python window Embedded, interactive Python window within ArcGIS Access to ArcPy, any Python functionality Great for experimenting with and learning Python

52 Executing a tool in Python ArcPy must be imported Follow syntax: arcpy.toolname_toolboxalias() Enter input and output parameters # Import ArcPy import arcpy # Set workspace environment arcpy.env.workspace = C:/Data # Execute Geoprocessing tool arcpy.buffer_analysis( roads.shp", roads_buffer.shp", 50 Meters )

53 Getting tool syntax Results window, Copy as Python Snippet Export Model to Python script Drag tool into Python window Tool documentation arcpy.usage( Buffer_analysis )

54 Setting environments in Python Accessed from arcpy.env Common environments: Workspace, coordinate system, extent Examples: arcpy.env.workspace arcpy.env.outputcoordinatesystem arcpy.env.extent

55 Live Demo Live demonstration of running geoprocessing functions in ArcMap

56 Geoprocessing messages Tools return three types of messages: Informative messages Warning messages Error messages Displayed in the ArcGIS Python window arcpy.getmessages() GetMessages(): All messages GetMessages(0): Only informative messages GetMessages(1): Only warning messages GetMessages(2): Only error messages

57 ArcPy functions: GetMessages # Execute Geoprocessing tool arcpy.buffer_analysis( roads.shp", roads_buffer.shp", 50 Meters ) # Print the execution messages print arcpy.getmessages() Executing: Buffer roads.shp roads_buffer.shp 50 Meters Start Time: Tue July 13 13:52: Executing (Buffer) successfully. End Time: Tue July 13 13:52: (Elapsed Time: 5.00

58 Error handling basics Why do errors occur? Incorrect tool use Typos Syntax errors Python error handling Try Except try: # Do Something except: # A failure occurred, do something else

59 Try, Except Statement # Start Try block try: arcpy.buffer_analysis( roads.shp", roads_buffer.shp", 50 Meters ) # If an error occurs except: # Print that Buffer failed and why print "Buffer failed print arcpy.getmessages(2)

60 Live Demo Live demonstration of error handling in Python/ArcPy

61 Geoprocessing Tasks

62

63 ArcPy functions Perform useful scripting tasks Print geoprocessing messages (GetMessages) List data to aid batch processing (ListFeatureClasses, ListFields; 12 total List functions) Getting data properties (Describe) Allow automation of manual tasks

64 Batch processing Run a geoprocessing operation multiple times with some automation Example: Using the Clip tool to clip every feature class in a workspace to a boundary List functions used in Python to perform batch processing

65 ArcPy functions: ListFeatureClasses # Set the workspace arcpy.env.workspace = C:/Data/FileGDB.gdb/FDs" # Get a list of all polygon feature classes fclist = arcpy.listfeatureclasses("*", "polygon") # Print the list of feature classes one at a time for fc in fclist: print fc

66 ArcPy functions: ListFields # List all fields in a feature class fields = arcpy.listfields( C:/Data/roads.shp") # loop through all the fields for field in fields: # print the field s name and field type print field.name, field.type Field objects have properties name, aliasname, domain, editable, hasindex, isnullable, isunique, length, precision, scale, type

67 ArcPy functions: Describe Returns an object with properties Allows script to determine properties of data Data type (shapefile, coverage, network dataset, etc.) Shape type (point, polygon, line, etc.) Spatial reference Extent of features Path

68 ArcPy functions: Describe # Describe a feature class desc = arcpy.describe( C:/Data/roads.shp") # Branch script logic based on ShapeType property if desc.shapetype == "Polyline" : print "The fc is a line feature class elif desc.shapetype == "Polygon" : print "The fc is a polygon feature class else: print The fc is not a line or polygon."

69 Receiving arguments Arguments are inputs to a script - Makes script more flexible and portable - Values passed to script from user, instead of hard-coded Use GetParameterAsText to read arguments - Zero-based index Connect script to an ArcGIS script tool

70 Receiving arguments # Create variables from input arguments inputfc = arcpy.getparameterastext(0) outputfc = arcpy.getparameterastext(1) # First and third parameters come from arguments arcpy.clip_analysis(inputfc, C:/Data/boundary.shp", outputfc)

71 Python scripting resources ArcGIS Resource Centers Online documentation Geoprocessing Resource Center: script gallery, blog, presentations Python Reference Books Learning Python by Mark Lutz & David Ascher Core Python Programming by Wesley J. Chun Python Organization DiveIntoPython.org Free tutorial:

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

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

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

Python Getting Started

Python Getting Started 2013 Esri International User Conference July 8 12, 2013 San Diego, California Technical Workshop Python Getting Started Drew Flater, Ghislain Prince Esri UC2013. Technical cal Workshop op. Does this describe

More information

Some material adapted from Upenn cmpe391 slides and other sources

Some material adapted from Upenn cmpe391 slides and other sources Some material adapted from Upenn cmpe391 slides and other sources History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Some material adapted from Upenn cmpe391 slides and other sources Invented in the Netherlands,

More information

Python Getting Started

Python Getting Started Esri European User Conference October 15-17, 2012 Oslo, Norway Hosted by Esri Official Distributor Python Getting Started Jason Pardy Does this describe you? New to Python Comfortable using ArcGIS but

More information

Python: Getting Started. Ben

Python: Getting Started. Ben Python: Getting Started Ben Ramseth bramseth@esri.com @esrimapninja E M E R A L D S A P P H I R E T H A N K Y O U T O O UR SPONSORS Topics covered What s is python? Why use python? Basics of python ArcPy

More information

Ways to Fail this Class. Welcome! Questions? Course Policies. CSC 9010: Natural Language Processing. Who / what / where / when / why / how 1/9/2014

Ways to Fail this Class. Welcome! Questions? Course Policies. CSC 9010: Natural Language Processing. Who / what / where / when / why / how 1/9/2014 Welcome! About me Max Peysakhov, Adjunct Faculty, CS Email: mpeysakhov@gmail.com Office: N/A Office hours:wed 5-6PM, or email for appt. About this course Syllabus, timeline, & resources on-line... http://edge.cs.drexel.edu/people/peysakhov/classes/cs260/

More information

Python Interpreted language: work with an evaluator for language expressions (like DrJava, but more flexible) Dynamically typed

Python Interpreted language: work with an evaluator for language expressions (like DrJava, but more flexible) Dynamically typed Full Python Tutorial Developed by Guido van Rossum in the early 1990s Named after Monty Python Available on eniac Available for download from http://www.python.org 2 Python Interpreted language: work with

More information

Full Python Tutorial. Python. Language features. Dynamic typing the key difference. Why Python? Introduction to Programming Languages and Techniques

Full Python Tutorial. Python. Language features. Dynamic typing the key difference. Why Python? Introduction to Programming Languages and Techniques Introduction to Programming Languages and Techniques Full Python Tutorial Developed by Guido van Rossum in the early 990s Named after Monty Python Available on eniac Available for download from http://www.python.org

More information

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2011 Python Python was developed

More information

Using Python with ArcGIS

Using Python with ArcGIS Using Python with ArcGIS Jason Pardy (jpardy@esri.com) Esri UC2013. Technical Workshop. Agenda A whirlwind tour Python Essentials Using Python in ArcGIS Python Tools Accessing Data Map Automation ArcGIS

More information

Table of Contents EVALUATION COPY

Table of Contents EVALUATION COPY Table of Contents Introduction... 1-2 A Brief History of Python... 1-3 Python Versions... 1-4 Installing Python... 1-5 Environment Variables... 1-6 Executing Python from the Command Line... 1-7 IDLE...

More information

And Parallelism. Parallelism in Prolog. OR Parallelism

And Parallelism. Parallelism in Prolog. OR Parallelism Parallelism in Prolog And Parallelism One reason that Prolog is of interest to computer scientists is that its search mechanism lends itself to parallel evaluation. In fact, it supports two different kinds

More information

ENGR 101 Engineering Design Workshop

ENGR 101 Engineering Design Workshop ENGR 101 Engineering Design Workshop Lecture 2: Variables, Statements/Expressions, if-else Edgardo Molina City College of New York Literals, Variables, Data Types, Statements and Expressions Python as

More information

Senthil Kumaran S

Senthil Kumaran S Senthil Kumaran S http://www.stylesen.org/ Agenda History Basics Control Flow Functions Modules History What is Python? Python is a general purpose, object-oriented, high level, interpreted language Created

More information

CSCE 110 Programming I

CSCE 110 Programming I CSCE 110 Programming I Basics of Python (Part 1): Variables, Expressions, and Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2013 Tiffani

More information

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

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an  . Michigan State University CSE 231, Fall 2013 CSE 231, Rich Enbody Office Hours After class By appointment send an email 2 1 Project 1 Python arithmetic Do with pencil, paper and calculator first Idle Handin Help room 3 What is a Computer Program?

More information

Using Python with ArcGIS

Using Python with ArcGIS Using Python with ArcGIS Drew Flater, Nobbir Ahmed Offering 184 Agenda Python essentials Arcpy, functions & classes Script geoprocessing workflows Automate map management & production Customize Desktop

More information

The current topic: Python. Announcements. Python. Python

The current topic: Python. Announcements. Python. Python The current topic: Python Announcements! Introduction! reasons for studying languages! language classifications! simple syntax specification Object-oriented programming: Python Types and values Syntax

More information

CIS192: Python Programming

CIS192: Python Programming CIS192: Python Programming Introduction Harry Smith University of Pennsylvania January 18, 2017 Harry Smith (University of Pennsylvania) CIS 192 Lecture 1 January 18, 2017 1 / 34 Outline 1 Logistics Rooms

More information

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

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes 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

More information

Using Python with ArcGIS

Using Python with ArcGIS Using Python with ArcGIS Jason Pardy (jpardy@esri.com) Javier Abadia (javier.abadia@esri.es) Esri UC2013. Technical Workshop. Agenda A whirlwind tour Jason: Python Essentials Using Python in ArcGIS Python

More information

Getting started with programming For geospatial data analysis. Robert Hijmans UC Davis

Getting started with programming For geospatial data analysis. Robert Hijmans UC Davis Getting started with programming For geospatial data analysis Robert Hijmans UC Davis Crash course for the CSI Cali, 22 Sept 2017 Developing computer programs for geographic data manipulation to get: -

More information

Programming to Python

Programming to Python Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the

More information

Basic Syntax - First Program 1

Basic Syntax - First Program 1 Python Basic Syntax Basic Syntax - First Program 1 All python files will have extension.py put the following source code in a test.py file. print "Hello, Python!";#hello world program run this program

More information

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr 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

More information

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline Python Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar December 28, 2011 1 Outline Introduction Installation and Use Distinct Features Python Basics Functional Example Comparisons with

More information

Introduction to Python

Introduction to Python Introduction to Python EECS 4415 Big Data Systems Tilemachos Pechlivanoglou tipech@eecs.yorku.ca 2 Background Why Python? "Scripting language" Very easy to learn Interactive front-end for C/C++ code Object-oriented

More information

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS 1439-1440 1 Outline 1. Introduction 2. Why Python? 3. Compiler and Interpreter 4. The first program 5. Comments and Docstrings 6. Python Indentations

More information

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction ECE 364 Software Engineering Tools Lab Lecture 3 Python: Introduction 1 Introduction to Python Common Data Types If Statements For and While Loops Basic I/O Lecture Summary 2 What is Python? Python is

More information

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

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Introduction to Python - Part I CNV Lab

Introduction to Python - Part I CNV Lab Introduction to Python - Part I CNV Lab Paolo Besana 22-26 January 2007 This quick overview of Python is a reduced and altered version of the online tutorial written by Guido Van Rossum (the creator of

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

What Version Number to Install

What Version Number to Install A Python Primer This chapter provides a quick overview of the Python language. The goal in this chapter is not to teach you the Python language excellent books have been written on that subject, such as

More information

S206E Lecture 19, 5/24/2016, Python an overview

S206E Lecture 19, 5/24/2016, Python an overview S206E057 Spring 2016 Copyright 2016, Chiu-Shui Chan. All Rights Reserved. Global and local variables: differences between the two Global variable is usually declared at the start of the program, their

More information

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

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts COMP519 Web Programming Lecture 17: Python (Part 1) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology Introduction to Python Part 1 Brian Gregor Research Computing Services Information Services & Technology RCS Team and Expertise Our Team Scientific Programmers Systems Administrators Graphics/Visualization

More information

Play with Python: An intro to Data Science

Play with Python: An intro to Data Science Play with Python: An intro to Data Science Ignacio Larrú Instituto de Empresa Who am I? Passionate about Technology From Iphone apps to algorithmic programming I love innovative technology Former Entrepreneur:

More information

Getting Started with Python

Getting Started with Python Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Python for C programmers

Python for C programmers Python for C programmers The basics of Python are fairly simple to learn, if you already know how another structured language (like C) works. So we will walk through these basics here. This is only intended

More information

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

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

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

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

A Brief Introduction to Python for those who know Java. (Last extensive revision: Daniel Moroz, fall 2015)

A Brief Introduction to Python for those who know Java. (Last extensive revision: Daniel Moroz, fall 2015) A Brief Introduction to Python for those who know Java (Last extensive revision: Daniel Moroz, fall 2015) Plan Day 1 Baby steps History, Python environments, Docs Absolute Fundamentals Objects, Types Math

More information

Algorithms and Programming I. Lecture#12 Spring 2015

Algorithms and Programming I. Lecture#12 Spring 2015 Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your

More information

Introduction to Python

Introduction to Python Introduction to Python خانه ریاضیات اصفهان فرزانه کاظمی زمستان 93 1 Why Python? Python is free. Python easy to lean and use. Reduce time and length of coding. Huge standard library Simple (Python code

More information

CS Programming Languages: Python

CS Programming Languages: Python CS 3101-1 - Programming Languages: Python Lecture 5: Exceptions / Daniel Bauer (bauer@cs.columbia.edu) October 08 2014 Daniel Bauer CS3101-1 Python - 05 - Exceptions / 1/35 Contents Exceptions Daniel Bauer

More information

Python Crash-Course. C. Basso. Dipartimento di Informatica e Scienze dell Informazione Università di Genova. December 11, 2007

Python Crash-Course. C. Basso. Dipartimento di Informatica e Scienze dell Informazione Università di Genova. December 11, 2007 Python Crash-Course C. Basso Dipartimento di Informatica e Scienze dell Informazione Università di Genova December 11, 2007 Basso (DISI) Python Crash-Course December 11, 2007 1 / 26 What is Python? Python

More information

CIS192 Python Programming. Robert Rand. August 27, 2015

CIS192 Python Programming. Robert Rand. August 27, 2015 CIS192 Python Programming Introduction Robert Rand University of Pennsylvania August 27, 2015 Robert Rand (University of Pennsylvania) CIS 192 August 27, 2015 1 / 30 Outline 1 Logistics Grading Office

More information

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s PYTHON FO R K I D S A P l ay f u l I n t r o d u c t i o n to P r o g r a m m i n g Jason R. Briggs Index Symbols and Numbers + (addition operator), 17 \ (backslash) to separate lines of code, 235 in strings,

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

More information

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python Outline 1 On Python language 2 3 4 Marcin Młotkowski Object oriented programming 1 / 52 On Python language The beginnings of Pythons 90 CWI Amsterdam, Guido van Rossum Marcin Młotkowski Object oriented

More information

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Introduction to: Computers & Programming: Review prior to 1 st Midterm Introduction to: Computers & Programming: Review prior to 1 st Midterm Adam Meyers New York University Summary Some Procedural Matters Summary of what you need to Know For the Test and To Go Further in

More information

Python Programming, bridging course 2011

Python Programming, bridging course 2011 Python Programming, bridging course 2011 About the course Few lectures Focus on programming practice Slides on the homepage No course book. Using online resources instead. Online Python resources http://www.python.org/

More information

Introduction to Python for Plone developers

Introduction to Python for Plone developers Plone Conference, October 15, 2003 Introduction to Python for Plone developers Jim Roepcke Tyrell Software Corporation What we will learn Python language basics Where you can use Python in Plone Examples

More information

Fundamentals of Programming (Python) Getting Started with Programming

Fundamentals of Programming (Python) Getting Started with Programming Fundamentals of Programming (Python) Getting Started with Programming Ali Taheri Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

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

Statements 2. a operator= b a = a operator b Statements 2 Outline Note: i=i+1 is a valid statement. Don t confuse it with an equation i==i+1 which is always false for normal numbers. The statement i=i+1 is a very common idiom: it just increments

More information

Flow Control: Branches and loops

Flow Control: Branches and loops Flow Control: Branches and loops In this context flow control refers to controlling the flow of the execution of your program that is, which instructions will get carried out and in what order. In the

More information

CS1 Lecture 3 Jan. 18, 2019

CS1 Lecture 3 Jan. 18, 2019 CS1 Lecture 3 Jan. 18, 2019 Office hours for Prof. Cremer and for TAs have been posted. Locations will change check class website regularly First homework assignment will be available Monday evening, due

More information

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

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why

More information

Python in 10 (50) minutes

Python in 10 (50) minutes Python in 10 (50) minutes https://www.stavros.io/tutorials/python/ Python for Microcontrollers Getting started with MicroPython Donald Norris, McGrawHill (2017) Python is strongly typed (i.e. types are

More information

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

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han Lab 1: Course Intro, Getting Started with Python IDLE Ling 1330/2330 Computational Linguistics Na-Rae Han Objectives Course Introduction http://www.pitt.edu/~naraehan/ling1330/index.html Student survey

More information

Variables, expressions and statements

Variables, expressions and statements Variables, expressions and statements 2.1. Values and data types A value is one of the fundamental things like a letter or a number that a program manipulates. The values we have seen so far are 2 (the

More information

CS1 Lecture 3 Jan. 22, 2018

CS1 Lecture 3 Jan. 22, 2018 CS1 Lecture 3 Jan. 22, 2018 Office hours for me and for TAs have been posted, locations will change check class website regularly First homework available, due Mon., 9:00am. Discussion sections tomorrow

More information

Lecture 4. Defining Functions

Lecture 4. Defining Functions Lecture 4 Defining Functions Academic Integrity Quiz Reading quiz about the course AI policy Go to http://www.cs.cornell.edu/courses/cs11110/ Click Academic Integrity in side bar Read and take quiz in

More information

Introduction to Python

Introduction to Python Introduction to Python CB2-101 Introduction to Scientific Computing November 11 th, 2014 Emidio Capriotti http://biofold.org/emidio Division of Informatics Department of Pathology Python Python high-level

More information

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15 1 LECTURE 1: INTRO Introduction to Scientific Python, CME 193 Jan. 9, 2014 web.stanford.edu/~ermartin/teaching/cme193-winter15 Eileen Martin Some slides are from Sven Schmit s Fall 14 slides 2 Course Details

More information

Python: common syntax

Python: common syntax Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

Building tools with Python

Building tools with Python Esri International User Conference San Diego, California Technical Workshops 7/25/2012 Building tools with Python Dale Honeycutt Session description Building Tools with Python A geoprocessing tool does

More information

Chapter 2 Writing Simple Programs

Chapter 2 Writing Simple Programs Chapter 2 Writing Simple Programs Charles Severance Textbook: Python Programming: An Introduction to Computer Science, John Zelle (www.si182.com) Software Development Process Figure out the problem - for

More information

Lecture 3. Functions & Modules

Lecture 3. Functions & Modules Lecture 3 Functions & Modules Labs this Week Lab 1 is due at the beginning of your lab If it is not yet by then, you cannot get credit Only exception is for students who added late (Those students should

More information

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu/program/philippines-summer-2012/ Philippines Summer 2012 Lecture 1 Introduction to Python June 19, 2012 Agenda About the Course What is

More information

Introduction to Python, Cplex and Gurobi

Introduction to Python, Cplex and Gurobi Introduction to Python, Cplex and Gurobi Introduction Python is a widely used, high level programming language designed by Guido van Rossum and released on 1991. Two stable releases: Python 2.7 Python

More information

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu) I. INTERACTIVE MODE VERSUS SCRIPT MODE There are two ways to use the python interpreter: interactive mode and script mode. 1. Interactive Mode (a) open a terminal shell (terminal emulator in Applications

More information

Introduction to Python

Introduction to Python Introduction to Python Jon Kerr Nilsen, Dmytro Karpenko Research Infrastructure Services Group, Department for Research Computing, USIT, UiO Why Python Clean and easy-to-understand syntax alldata = cpickle.load(open(filename1,

More information

Using Python in ArcGIS Oli Helm May 2, 2013

Using Python in ArcGIS Oli Helm May 2, 2013 Using Python in ArcGIS 10.1 Oli Helm May 2, 2013 ohelm@esri.ca Today s Agenda This seminar is designed to help you understand: 1) Python Essentials 2) What s new in Python in ArcGIS 10.1 3) Python Add-Ins

More information

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi Shell / Python Tutorial CS279 Autumn 2017 Rishi Bedi Shell (== console, == terminal, == command prompt) You might also hear it called bash, which is the most widely used shell program macos Windows 10+

More information

Short, Unique and Mysterious

Short, Unique and Mysterious Short, Unique and Mysterious Q Why is the Programming Language named so? a Monty Python's Flying Circus "A t t h e t i m e w h e n h e b e g a n implementing Python, Guido van R o s s u m w a s a l s o

More information

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

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike

More information

STSCI Python Introduction. Class URL

STSCI Python Introduction. Class URL STSCI Python Introduction Class 2 Jim Hare Class URL www.pst.stsci.edu/~hare Each Class Presentation Homework suggestions Example files to download Links to sites by each class and in general I will try

More information

High Level Scripting. Gino Tosti University & INFN Perugia. 06/09/2010 SciNeGhe Data Analysis Tutorial

High Level Scripting. Gino Tosti University & INFN Perugia. 06/09/2010 SciNeGhe Data Analysis Tutorial High Level Scripting Part I Gino Tosti University & INFN Perugia What is a script? Scripting Languages It is a small program able to automate a repetitive and boring job; It is a list of commands that

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 1 Introduction to Python Agenda What is Python? and Why Python? Basic Syntax Strings User Input Useful

More information

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

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department 0901212 Python Programming 1 st Semester 2014/2015 Course Catalog This course introduces

More information

Not-So-Mini-Lecture 6. Modules & Scripts

Not-So-Mini-Lecture 6. Modules & Scripts Not-So-Mini-Lecture 6 Modules & Scripts Interactive Shell vs. Modules Launch in command line Type each line separately Python executes as you type Write in a code editor We use Atom Editor But anything

More information

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

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Introduction to Python

Introduction to Python Introduction to Python Why is Python? Object-oriented Free (open source) Portable Powerful Mixable Easy to use Easy to learn Running Python Immediate mode Script mode Integrated Development Environment

More information

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

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2 Basic Concepts Computer Science Computer - Science - Programming history Algorithms Pseudo code 2013 Andrew Case 2 Basic Concepts Computer Science Computer a machine for performing calculations Science

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Learning Objectives by Week 1 ENGR 102 Engineering Lab I Computation 2 Credits 2. Introduction to the design and development of computer applications for engineers;

More information

MUTABLE LISTS AND DICTIONARIES 4

MUTABLE LISTS AND DICTIONARIES 4 MUTABLE LISTS AND DICTIONARIES 4 COMPUTER SCIENCE 61A Sept. 24, 2012 1 Lists Lists are similar to tuples: the order of the data matters, their indices start at 0. The big difference is that lists are mutable

More information

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

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s Intro to Python Python Getting increasingly more common Designed to have intuitive and lightweight syntax In this class, we will be using Python 3.x Python 2.x is still very popular, and the differences

More information

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1 The Three Rules Chapter 1 Beginnings Rule 1: Think before you program Rule 2: A program is a human-readable essay on problem solving that also executes on a computer Rule 3: The best way to improve your

More information

CS Summer 2013

CS Summer 2013 CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or

More information

Lists, loops and decisions

Lists, loops and decisions Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence

More information

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu) I. INTERACTIVE MODE VERSUS SCRIPT MODE There are two ways to use the python interpreter: interactive mode and script mode. 1. Interactive Mode (a) open a terminal shell (terminal emulator in Applications

More information

Python Unit

Python Unit Python Unit 1 1.1 1.3 1.1: OPERATORS, EXPRESSIONS, AND VARIABLES 1.2: STRINGS, FUNCTIONS, CASE SENSITIVITY, ETC. 1.3: OUR FIRST TEXT- BASED GAME Python Section 1 Text Book for Python Module Invent Your

More information