Functions Reading/writing files Catching exceptions

Slides:



Advertisements
Similar presentations
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Advertisements

The Web Warrior Guide to Web Design Technologies
COMP234 Perl Printing Special Quotes File Handling.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Introduction to Python
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
CTEC 1863 – Operating Systems Shell Scripting. CTEC F2 Overview How shell works Command line parameters –Shift command Variables –Including.
Python Programming Fundamentals
Python & ModelBuilder. Continuing Education Python and ModelBuilder Overview Python/ModelBuilder Concepts –The Geoprocessor –Checking some environment.
Esri International User Conference | San Diego, CA Technical Workshops | Python – Getting Started Drew Flater, Ghislain Prince July 12 - July 14, 2011.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 13 Files and Exception Handling 1.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
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.
17. Python Exceptions Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Input, Output, and Processing
If statements while loop for loop
Chapter 24 Exception CSC1310 Fall Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Python Functions.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
JavaScript, Fourth Edition
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Artificial Intelligence Lecture No. 26 Dr. Asad Ali Safi ​ Assistant Professor, Department of Computer Science, COMSATS Institute of Information Technology.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Agenda Positional Parameters / Continued... Command Substitution Bourne Shell / Bash Shell / Korn Shell Mathematical Expressions Bourne Shell / Bash Shell.
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.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Firoze Abdur Rakib. Syntax errors, also known as parsing errors, are perhaps the most common kind of error you encounter while you are still learning.
CS 127 Exceptions and Decision Structures. Exception Handling This concept was created to allow a programmer to write code that catches and deals with.
Lecture 4 Python Basics Part 3.
Python Built-in Exceptions Data Fusion Albert Esterline Source:
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
CSx 4091 – Python Programming Spring 2013 Lecture L2 – Introduction to Python Page 1 Help: To get help, type in the following in the interpreter: Welcome.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 9: Value-Returning Functions
C++ Exceptions.
Chapter 8 Text Files We have, up to now, been storing data only in the variables and data structures of programs. However, such data is not available.
Lecture 4 Python Basics Part 3.
Why exception handling in C++?
Variables, Expressions, and IO
Functions CIS 40 – Introduction to Programming in Python
Exceptions and files Taken from notes by Dr. Neil Moore
PH2150 Scientific Computing Skills
Exception Handling Chapter 9.
Python Primer 2: Functions and Control Flow
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Exceptions and files Taken from notes by Dr. Neil Moore
Lecture 4 Python Basics Part 3.
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
COMPUTER PROGRAMMING SKILLS
Topics Introduction to File Input and Output
Presentation transcript:

Functions Reading/writing files Catching exceptions Python language Functions Reading/writing files Catching exceptions

Function Definition def function_name (arg1, arg2, …) : # arg means argument or parameter! body # Sometimes we pass a known value for one of the arguments: def function_name (arg1, arg2=default2, arg3): # e.g., power (x, y=3)

Function with docsting

Function modifies a string

Pass arguments by position

Casting user’s entered value

Function traverses a string with a loop

Using datetime functions The age function uses the input function to get the birth year. It then imports the datetime module Gets the current year form the now () function. Calculates the age, and returns it

Built in Numeric Functions abs(), divmod(), float(), hex(), long(), max(), min(), oct(), pow(), round() # there are a lot more for trigonometry, etc. ‘none’ is a special data type for empty value e.g., when a function does not return a value It is used as a placeholder

Find maximum of any unknown set of arguments Notice that the function is called with different numbers of arguments. The * does the trick!

Defining a global variable Notice that calling the local variable outside of the function leads to error!

Assigning the returned value of a function to a variable

Tools in Arcpy are function! Tools have name, which is similar to the tool’s label in ArcGIS (without space), for example: AddField for the Add Field tool The alias for a tool is not the same as its name or label. It is a short version of it, for example: ‘management’ is the alias for Data Management toolbox Clip_management is the Clip tool in the Data Management toolbox

Two ways to access a tool in ArcGIS All tools are available as function in Arcpy Each tool (function) does a specific task To access a tool, we can: 1. Call its corresponding function arcpy.toolname_toolboxalias (arguments) For example: call the Clip tool: >>> import arcpy >>> arcpy.env.workspace = “C:/Data” >>> arcpy.Clip_analysis (“stream.shp”, “study.shp”, “result.shp”) Another example: >>> arcpy.env.workspace = “C:/Data/study.gdb” >>> arcpy.Buffer_analysis (“roads”, “buffer”, “100 METERS”)

Functions in ArcGIS – GetMessages() When a tool is run in ArcGIS, messages write about its success or failure To get the message, we use the following functions: >>> arcpy.GetMessages () >>> print arcpy.GetMessages (0) # 1st message >>> count = arcpy.GetMessageCount () >>> print arcpy.GetMessage (count-1) # prints the last message

2. Tools are also in modules that match the toolbox alias name arcpy.toolboxalias.toolname (arguments) For example: >>> import arcpy >>> arcpy.env.workspace = “C:/Data” >>> arcpy.analysis.Clip (“stream.shp”, “study.shp”, “result.shp”) These two methods are equivalent! It depends on our preference.

Other examples >>> import arcpy >>> arcpy.env.workspace = “C:/Data” >>> infc = “streams.shp” # fc stands for feature class >>> clipfc = “study.shp” >>> outfc = “result.shp” >>> count = arcpy.GetCount_management (infc, clipfc, outfc) >>> print count # prints the count for streams >>> result = arcpy.analysis.Clip (infc, clipfc, outfc) >>> print result # prints an object # will print the path to the result shape file, i.e., : C:/Data/result.shp

Filesystem Filesystem refers to naming, creating, moving, or referring to files. Depends on the operating system. Pathname: String that refers to the location of the file in a directory Filesystem in all operating systems is a tree structure, made of a root (disk), directory, subdirectory, and its branches. In Windows, the \ character is used to separate the file or directory names from each other. There is a separate root for each drive (A:\, C:\, D:\) For example: C:\myDirectory\myfile

Paths in Python In Python, backslash (\) is used for escape. For example, \n and \t for line feed and tab Therefore, we avoid using \ in Python paths. Instead: We use forward slash; C:/Data/Exercise01.txt Or, we use double backslash (\\) C:\\Data\\Exercise01.txt OR, use a string litteral: #put ‘r’ before the string. r means raw string r”C:\Data\Exercise01.txt” Paths are stored as string in Python! For example, the following assigns the path to a shape file as a string for the inputfc variable (fc is feature class in ArcGIS) >>> Inputfc = “C:/Data/lakes.shp”

Absolute path vs. relative path Absolute path is the exact address of the file in the filesystem, starting from the root. C:\Geoinformatics\myFile.txt A:\Courses\Python\Programming.html Relative path writes it with respect to another point in the file system Python\Functions\map.txt We can either append a relative path to an existing absolute path. Or, we can implicitly reference the current working directory where a Python program may consider to be during an execution.

Current working directory - cwd Python knows the current directory of the file it is working on (just like you know when you work on a file that you open from a directory). This directory is called the ‘current working directory” or cwd for a program. Do the following to get the cwd of Python on your computer

Opening files in read mode

Opening a file in the write mode We pass ‘w’ instead of ‘r’ in the 2nd argument This will first erase data in the file before writing. NOTE: If we want to append to the file, use ‘a’ instead of ‘w’.

Open File - example >>> f = open ("C:/Data/mytext.txt", "w") >>> f.write ("GIS") >>> f = open ("C:/Data/mytext.txt", "r") >>> f.read() 'GIS‘

Read the number of lines in a file Assume the multi_line.txt file has five words written in five lines

Screen input/output Input () is a built-in method to prompt for input; returns a string

Throwing exceptions (Error handling) Are used to handle unusual circumstances (e.g., errors) encountered during the execution of the program. We have to realize that errors will happen, and write code to detect and handle them. This is done by returning a status value by a function to indicate whether a function was executed successfully or not

Raising (throwing) an exception try : # if there is no problem, do your operations here # … except : # execute this block if there is any exception (problem) # handle possible problem here else : # If there is no exception, execute this block finally : # this always will execute. # used to manage resources (e.g., # close files).

General try/except try: statements # Run this main action first except name1: statements # Run if name1 is raised during the try block except (name2, name3): statements # Run if any of these exceptions occur except: statements # Run for all (other) exceptions raised else: statements # Run if no exception was raised during try block

try : body # is executed first try : body # is executed first. # If successful (no error), the else block is executed, and try is finished # If exception is thrown in try, the 1st except clause is searched except exception_type1 as var1 : # if this clause matches the error, # the error is assigned to the variable var1 after the exception type, # and the exception code below the associated type is executed exception code1 # handle the raised exception, otherwise: except exception_type2 as var2 : # comes to here if the first except clause did not match. exception code2 # this may process if it matches … # and so on else : # if there is no error, come here, this is optional, and rarely used else_body finally : # optional. If it exists, it always executes finally_body # clean up by closing files or resetting variables

Common exception errors and examples IOError If the file cannot be opened or read. print (“Error while reading the file”) ImportError If python cannot find the module print (“no module found”) ValueError Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value print (“non-numeric data found”) KeyboardInterrupt Raised when the user hits the interrupt key (normally Control-C or Delete) print (“you cancelled the operation”) EOFError Raised when one of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without reading any data print (“end of file”)

Handle ValueError

Assign exception to variable

Handle ValueError … Example: Define a function to get a number from a user. Convert it into float If it cannot be converted to float, send a message

Exception is an object (as in OOP) Exceptions can be raised by any function and given to a variable >>> list = [2, 4, 6] >>> x = list[2] >>> print x 6 >>> x = list[4] # this raises the ‘list index out of range’ error Traceback (most recent call last): File "<interactive input>", line 1, in <module>IndexError: list index out of range The error is handled by Python by writing the above message, which in this case terminates the program because there is no exception handler!

Catching when knowing the type of error

Catching multiple error types

IOError

Handle opening file issues We use try/except for quality assurance (QA)

IOError …

IOError …

Catch all exception types

Python programs Up until now you have interactively used Pythonwin to communicate with the Python interpreter. A set of Python statements saved in a file constitutes a Python program or script. The program usually has a controlling function that can be called to run the program.