Lilian Blot TPOP Practical Assignment Optional, but you are strongly encourage to do it, especially if you are new to programming Available on Module.

Slides:



Advertisements
Similar presentations
Lilian Blot PART III: ITERATIONS Core Elements Autumn 2012 TPOP 1.
Advertisements

Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
Lilian Blot CORE ELEMENTS PART V: FUNCTIONS PARAMETERS & VARIABLES SCOPE Lecture 5 Autumn 2014 TPOP 1.
Lilian Blot TPOP Practical Assignment Optional, but you are strongly encourage to do it, especially if you are new to programming Available on Module webpage.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Exceptions COMPSCI 105 S Principles of Computer Science.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
Lists in Python.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
17. Python Exceptions Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Functions Reading/writing files Catching exceptions
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Chapter 24 Exception CSC1310 Fall Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically.
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
Built-in Data Structures in Python An Introduction.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 Dictionaries and Sets.
ICS 313: Programming Language Theory Chapter 14: Exceptions.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
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.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
Python Exceptions and bug handling Peter Wad Sackett.
Dictionaries Intro to Computer Science CS 1510 Dr. Sarah Diesburg.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
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.
Lecture 11 Dr. Eng. Ibrahim El-Nahry Exception Handling.
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Department of Computer Science,
Topics Introduction to Repetition Structures
Topics Introduction to File Input and Output
Python’s Errors and Exceptions
CISC101 Reminders Slides have changed from those posted last night…
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
Topics Sequences Introduction to Lists List Slicing
Dictionaries Dictionary: object that stores a collection of data
Python Syntax Errors and Exceptions
Topics Sequences Lists Copying Lists Processing Lists
CHAPTER 4: Lists, Tuples and Dictionaries
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Topics Introduction to Repetition Structures
By Ryan Christen Errors and Exceptions.
Topics Sequences Introduction to Lists List Slicing
Exception Handling COSC 1323.
Topics Introduction to File Input and Output
Presentation transcript:

Lilian Blot TPOP Practical Assignment Optional, but you are strongly encourage to do it, especially if you are new to programming Available on Module webpage from next week (week 6) Deadline: Friday 14 November at 12:00 pm.  submitted by to  with the subject: "TPOP Assignment“ Feedback and Mark given by appointment ONLY must improve / pass / good (2.1) / very good (1st) Autumn 2014 TPOP 1

Lilian Blot Open Surgery If you fill that you are struggling, sometime a 15 minutes face-to-face meeting helps to clear a lot of problems. I have reserved three sessions in week6 You can book a 15 minutes slot using the following link via Google calendar AppGoogle calendar App Autumn 2014 TPOP 2

Lilian Blot A word (or more) of Wisdom It’s the journey, not the destination. Could not find the author Sometime it’s the journey that teaches you a lot about your destination Drake (Rapper) Autumn 2014 TPOP 3

Lilian Blot CORE ELEMENTS PART VI: DICTIONARIES & HANDLING ERRORS Lecture 8 Autumn 2014 TPOP 4

Lilian Blot Overview Review on Iterables (list, strings, tuples) and loops Dictionaries  A new data type Handling Exceptions  try-except-else-finally Raising exceptions  raise Autumn 2014 TPOP 5

Lilian Blot Iterating through Lists We have seen two ways to traverse an iterable (list, string, tuple). Which one should we choose? Autumn 2014 TPOP 6 lst = [’a’,’b’,’c’,’d’] for val in lst: print val.upper() Code 1 lst = [’a’,’b’,’c’,’d’] for val in xrange(len(lst)): lst[val] = lst[val].upper() Code 2 The variable val will take the value ’a’, then ’b’, … The variable val will take the value 0, then 1, … READ READ/ASSIGN

Lilian Blot Iterating through Lists For the second code snippet, use a better name for the variable containing the index in the array.  index, pos, row, col, … Autumn 2014 TPOP 7 lst = [’a’,’b’,’c’,’d’] for val in lst: print val.upper() Code 1 lst = [’a’,’b’,’c’,’d’] for index in xrange(len(lst)): lst[index] = lst[index].upper() Code 2 The variable val will take the value ’a’, then ’b’, … The variable index will take the value 0, then 1, … READ READ/ASSIGN

Lilian Blot Iterating through Lists When using while remember to:  Initialise the index variable  Change the index variable (to avoid infinite loop) Autumn 2014 TPOP 8 lst = [’a’,’b’,’c’,’d’] index = 0 while index < len(lst): lst[index] = lst[index].upper() index = index + 1 Code 3 lst = [’a’,’b’,’c’,’d’] for index in xrange(len(lst)): lst[index] = lst[index].upper() Code 2

Lilian Blot ANOTHER PYTHON BUILT-IN TYPE Dictionaries Autumn 2014 TPOP 9

Lilian Blot Caesar Cipher Autumn 2014 TPOP 10 Alphabetabcdefg… Keycazbgdx…

Lilian Blot Be Cleverer than Brute Force Frequency analysis:  A way to identify symbols with similar frequencies Which Data representation?  [(‘a’, 8.167), (‘b’, 1.492)…] ? How to create the frequency table of the encrypted message?  Is our data representation efficient? We may need a new data structure Autumn 2014 TPOP 11

Lilian Blot Dictionaries A new built-in data structure Is MUTABLE Map a key to a value Keys must be immutable objects  int, float, string, tuple Values can be any object  list, dictionary, int, float, string, … Autumn 2013 TPOP 12

Lilian Blot How to Create/Use a Dictionary General form dict_name = {key1:value1, key2:value2, …} Retrieving a value: dict_name [key] adding/modifying a value: dict_name [key] = value deleting a value: del dict_name [key] Autumn 2013 TPOP 13

Lilian Blot Dictionaries A fast way to retrieve a value in a collection of values  Better than list, if we don’t know the index of the element to retrieve Adding an new element to a list is faster than adding it to a dictionary  As long as the list is not sorted Autumn 2014 TPOP 14

Lilian Blot Dictionaries How to apply this structure to our decoding problem?  What would be the keys?  What would be the values? Autumn 2014 TPOP 15

Lilian Blot HANDLING ERRORS Exceptions Autumn 2014 TPOP 16

Lilian Blot Why Use Exceptions? To Jump around arbitrarily large chunks of a program Error Handling  When an error is detected at runtime Event Notification  Can also be used to signal a valid condition Special-case Handling  When some condition may happen rarely Autumn 2014 TPOP 17

Lilian Blot A Simple Program see code ‘ user division first attempt ’ Autumn 2014 TPOP 18

Lilian Blot A Simple Program Dealing with user inputs  What if the user enters a invalid number format  An error occurs: ValueError  The program crashes Handling errors with try-except  see code ‘ user division second & third attempt ’ Autumn 2014 TPOP 19 try: except ErrorType: Code

Lilian Blot A Simple Program Handling many different type of errors with try-except  At most one handler will be executed  see code ‘ user division final attempt ’ Autumn 2014 TPOP 20 try: except ErrorTypeOne: except ErrorTypeTwo: except (ErrorTypeThree, ErrorTypeFour, ErrorTypeFive) : Code

Lilian Blot try-except-else The try... except statement has an optional else clause,  must follow all except clauses.  It is useful for code that must be executed if the try clause does not raise an exception. Autumn 2014 TPOP 21 try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close() Code

Lilian Blot try-finally The try statement has another optional clause  intended to define clean-up actions that must be executed under all circumstances.  A finally clause is always executed before leaving the try statement, whether an exception has occurred or not Autumn 2014 TPOP 22 try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines‘ finally: f.close() Code

Lilian Blot raise The raise statement allows the programmer to force a specified exception to occur. Autumn 2014 TPOP 23 def myDiv(numerator, divisor): if divisor == 0: raise ValueError(’argument divisor must not be 0’) else: return numerator/divisor Code

Lilian Blot raise If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of the raise statement allows you to re-raise the exception Autumn 2014 TPOP 24 try: f = open(arg, 'r') except IOError: print 'cannot open', arg raise Code

Lilian Blot Summary We have seen how to:  handle exception  raise exception Autumn 2014 TPOP 25

Lilian Blot Reading Handling Exceptions  built-in Exceptions list  exceptions exceptions Autumn 2014 TPOP 26

Lilian Blot Odds and Ends When an exception occurs, it may have an associated value, also known as the exception’s argument. The presence and type of the argument depend on the exception type. Autumn 2014 TPOP 27 try: f = open(arg, 'r') except IOError as instExc: # instExc is a variable that # can be inspected print 'cannot open', arg print ‘errors is:', instExc else: print arg, 'has', len(f.readlines()), 'lines' f.close() Code