Exceptions. raise type(message) raise Exception(message)

Similar documents
Exceptions. raise type(message) raise Exception(message)

Week 2. Classes and Objects

Fundamentals of Programming (Python) Object-Oriented Programming. Ali Taheri Sharif University of Technology Spring 2018

COMPSCI 105 S Principles of Computer Science. Classes 3

python 01 September 16, 2016

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

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

Advanced Python. Executive Summary, Session 1

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

Week 2. expressions, variables, for loops

Programming with Python

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

Python Lists. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 5, 2011

Python. Executive Summary

Operator Overloading. a flop = a floating-point operation overloading arithmetical operators counting number of flops in a sum

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Exam #3, Form 3 A CSE 231 Fall 2015 (1) DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

Iterators & Generators

CS 1301 Post Exam 3 Practice Spring 2016

MEIN 50010: Python Flow Control

CSC148 Intro. to Computer Science

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

Unit testing with pytest and nose 1

Lecture 38: Python. CS 51G Spring 2018 Kim Bruce

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

Lecture 18. Classes and Types

Introduction to Programming

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

61A Lecture 25. Friday, October 28

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Lecture 19: Subclasses & Inheritance (Chapter 18)

Lecture 21. Programming with Subclasses

Introduction to Python

Lecture 21. Programming with Subclasses

CircuitPython 101: Working with Lists, Iterators and Generators

Python Intro GIS Week 1. Jake K. Carr

CS 11 python track: lecture 4

Class Design (Section 9 of 17)

Lecture 18. Methods and Operations

Computational Physics

CS Lecture 26: Grab Bag. Announcements

20. More Complicated Classes. A Class For Manipulating Fractions. A Class For Manipulating Fractions 4/19/2016. Let s Define a Class to Do This Stuff

PREPARING FOR PRELIM 2

Question 2. [5 points] Given the following symbolic constant definition

Lecture 18: Using Classes Effectively (Chapter 16)

Python 1: Intro! Max Dougherty Andrew Schmitt

Introduction to Programming


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

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009

Conditional Control Structures. Dr.T.Logeswari

CS 234 Python Review Part 2

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

ECE 364 Software Engineering Tools Laboratory. Lecture 7 Python: Object Oriented Programming

Last Name: First: Netid: Section. CS 1110 Final, December 17th, 2014

Computational Mathematics with Python

Welcome to CSC148! Introduction to Computer Science

CIS192 Python Programming

Try and Error. Python debugging and beautification

CS177 Recitation. Functions, Booleans, Decision Structures, and Loop Structures

Lecture 21. Programming with Subclasses

Python Programming. Introduction Part II

Python Development with PyDev and Eclipse -

CSI33 Data Structures

CS61A Lecture 32. Amir Kamil UC Berkeley April 5, 2013

Talen en Compilers. Johan Jeuring , period 2. December 15, Department of Information and Computing Sciences Utrecht University

CIS192 Python Programming

Lessons on Python Functions

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

Organization of Programming Languages CS 3200/5200D. Lecture 12

Lessons on Python Classes and Objects

CIS192 Python Programming

Lab 8: Advanced Functions

ENCM 339 Fall 2017 Lecture Section 01 Lab 9 for the Week of November 20

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

Review 3. Exceptions and Try-Except Blocks

Introduction to Python, Cplex and Gurobi

Computer Organization & Systems Exam I Example Questions

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers

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

Lecture 17: Classes (Chapter 15)

Python for Astronomers. Errors and Exceptions

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

Lists How lists are like strings

Modules and scoping rules

Built-in Types of Data

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

CMSC201 Computer Science I for Majors

Object Oriented Programming in Python 3

CS 1110 Prelim 2 November 12th, 2015

Variable and Data Type I

CIS192 Python Programming

INFOB3TC Exam 2. Sean Leather. Monday, 30 January 2012, 17:00 20:00

Review 2. Classes and Subclasses

CIS192 Python Programming

Transcription:

Built-In Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/.0

Exceptions raise type(message) raise Exception(message) Exceptions AssertionError TypeError NameError ValueError IndexError SyntaxError ArithmeticError http://docs.python.org/library/exceptions.html#bltin-exceptions

str () We already know about the str () method that allows a class to convert itself into a string rectangle.py 5 6 7 8 9 class Rectangle: def init (self, x, y, width, height): self.x = x self.y = y self.width = width def str (self): return "(x=" + str(self.x) + ",y=" + str(self.y) + ",w=" + str(self.width) + ",h=" + str(self.height) + ")"

Underscored methods There are many other underscored methods that allow the built-in function of python to work Most of the time the underscored name matches the built-in function name Built-In str() len() abs() Class Method str () len () abs ()

First Class Citizens For built-in types like ints and strings we can use operators like + and *. Our classes so far were forced to take back routes and use methods like add() or remove() Python is super cool, in that it allows us to define the usual operators for our class This brings our classes up to first class citizen status just like the built in ones 5

Underscored methods There are underscore methods that you can implement in order to define logical operations and arithmetic operations Binary Operators Comparison Operators Operator Class Method - neg (self,other) + pos (self, other) * mul (self, other) / truediv (self, other) Unary Operators Operator Class Method - neg (self) + pos (self) Operator Class Method == eq (self,other)!= ne (self, other) < lt (self, other) > gt (self, other) <= le (self, other) >= ge (self, other) N/A nonzero (self) http://docs.python.org/reference/datamodel.html#sequence-types 6

ArrayIntList Operations Lets write a method that we could add to arrayintlist.py that would allow us to apply the /= operation to the list. The operation would simply divide all elements of the list by the argument of the operator Method: itruediv (self, num) Example run print(int_list) #[,,,, 5, 6, 7] int_list /= print(int_list) #[0.0,.0,.5,.0,.5,.0,.5] 7

Solution arrayintlist.py 5 6 7 def itruediv (self, num): if num == 0 : raise ArithmeticError( Can't divide by zero.") for i in list(range(len(self))) : self.elementdata[i] /= num return self 8

Lambda Sometimes you need a simply arithmetic function Its silly to write a method for it, but redundant not too With lambda we can create quick simple functions Facts Lambda functions can only be comprised of a single expression No loops, no calling other methods Lambda functions can take any number of variables Syntax: lambda param,,paramn : expression 9

Lambda Syntax lambda.py 5 6 7 8 9 0 #Example square_func = lambda x : x** square_func() #return: 6 #Example close_enough = lambda x, y : abs(x y) < close_enough(, ) #return: True #Example def get_func(n) : return lambda x : x * n + x % n my_func = get_func() my_func() #return: 56 0

Higher-Order Functions A higher-order function is a function that takes another function as a parameter They are higher-order because it s a function of a function Examples Map Reduce Filter Lambda works great as a parameter to higher-order functions if you can deal with its limitations

Filter filter(function, iterable) The filter runs through each element of iterable (any iterable object such as a List or another collection) It applies function to each element of iterable If function returns True for that element then the element is put into a List This list is returned from filter in versions of python under In python, filter returns an iterator which must be cast to type list with list()

Filter Example Example 5 6 nums = [0,, 7,,, 0, 9,, 5, 6, 8, 0, ] nums = list(filter(lambda x : x!= 0, nums)) print(nums) #[, 7,,, 9,, 5, 6, 8, ]

Filter Problem NaN = float("nan") scores = [[NaN,,.5, 78, math.pi], [,,.5,.7, math.pi / ], [, NaN,.5, 78, math.pi], [,,.5, 9, - math.pi]] Goal: given a list of lists containing answers to an algebra exam, filter out those that did not submit a response for one of the questions, denoted by NaN

Filter Problem Solution 5 6 7 8 9 0 NaN = float("nan") scores = [[NaN,,.5, 78, pi],[,,.5,.7, pi / ], [,NaN,.5, 78, pi],[,,.5, 9, - pi]] #solution - intuitive def has_nan(answers) : for num in answers : if isnan(float(num)) : return False return True valid = list(filter(has_nan, scores)) print(valid) #Solution sick python solution valid = list(filter(lambda x : NaN not in x, scores)) print(valid) 5

Map map(function, iterable,...) Map applies function to each element of iterable and creates a list of the results You can optionally provide more iterables as parameters to map and it will place tuples in the result list Map returns an iterator which can be cast to list 6

Map Example Example 5 6 7 nums = [0,, 7,,, 0, 9,, 5, 6, 8, 0, ] nums = list(map(lambda x : x % 5, nums)) print(nums) #[0,,,,, 0,,, 0,,, 0, ] 7

Map Problem Goal: given a list of three dimensional points in the form of tuples, create a new list consisting of the distances of each point from the origin Loop Method: - distance(x, y, z) = sqrt(x** + y** + z**) - loop through the list and add results to a new list 8

Map Problem Solution 5 6 7 8 9 from math import sqrt points = [(,, ), (5, 7, -), (,, 0), (9, 6, 8)] def distance(point) : x, y, z = point return sqrt(x** + y** + z**) distances = list(map(distance, points)) 9

Reduce reduce(function, iterable[,initializer]) Reduce will apply function to each element in iterable along with the sum so far and create a cumulative sum of the results function must take two parameters If initializer is provided, initializer will stand as the first argument in the sum Unfortunately in python reduce() requires an import statement from functools import reduce 0

Reduce Example Example 5 6 7 nums = [,,,, 5, 6, 7, 8] nums = list(reduce(lambda x, y : (x, y), nums)) Print(nums) #(((((((, ), ), ), 5), 6), 7), 8)

Reduce Problem Goal: given a list of numbers I want to find the average of those numbers in a few lines using reduce() For Loop Method: - sum up every element of the list - divide the sum by the length of the list

Reduce Problem Solution nums = [9, 7, 6,, 88, 8, 8, 9, 7, 7, 8, 6, 9,, 60, 7, 6, 59, 86, 56] sum = reduce(lambda x, y : x + y, nums) / len(nums)