 Name Space ◦ modname.funcname ◦ Main 의 module name: ‘__main__’ if __name__ == ‘__main__’:  Scopes.

Slides:



Advertisements
Similar presentations
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
Advertisements

Head First Python Chapter 4 Persistence: Saving Data to Files SNU IDB Lab.
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Exceptions COMPSCI 105 S Principles of Computer Science.
Floating point numbers in Python Floats in Python are platform dependent, but usually equivalent to an IEEE bit C “double” However, because the significand.
January 24, 2006And Now For Something Completely Different 1 “And Now For Something Completely Different” A Quick Tutorial of the Python Programming Language.
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
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.
 Name Space ◦ modname.funcname ◦ Main 의 module name: ‘__main__’ if __name__ == ‘__main__’:  Scopes.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Functions Reading/writing files Catching exceptions
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
PHP Workshop ‹#› PHP Error Handling. PHP Workshop ‹#› Types There are 12 unique error types, which can be grouped into 3 main categories: Informational.
By: Chris Harvey Python Classes. Namespaces A mapping from names to objects Different namespaces have different mappings Namespaces have varying lifetimes.
Cohesion and Coupling CS 4311
Chapter 8 More On Functions. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. First cut, scope.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
Before starting OOP… Today: Review Useful tips and concepts (based on CS 11 Python track, CALTECH)
Sistem Operasi © Sekolah Tinggi Teknik Surabaya 1.
An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python
P YTHON ’ S C LASSES Ian Wynyard. I NTRODUCTION TO C LASSES A class is the scope in which code is executed A class contains objects and functions that.
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
CS2021 Week 2 Off and Running with Python. Two ways to run Python The Python interpreter – You type one expression at a time – The interpreter evaluates.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
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)
Python Let’s get started!.
Scope, Aliasing, Tuples & Mutability Intro2CS – week 4a 1.
Exceptions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
James Tam Introduction To Files In Python In this section of notes you will learn how to read from and write to files in your programs.
Lecture 4 Python Basics Part 3.
LECTURE 7 The Standard Library Part 1: Built-ins, time, sys, and os.
Python’s Standard Library Part 2 Francis Ryan. Output formatting, 1 repr module – When using large or deeply nested containers, allows better printing.
Python Exceptions and bug handling Peter Wad Sackett.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
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.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
Python Basics 본 자료는 다음의 웹 사이트를 정리 한 내용이니 참조 바랍니다. ythonBasics.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
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.
Indentations makes the scope/block Function definition def print_message (): print “hello” Function usages print_message () hubo.move ()// hubo is a class.
Rajkumar Jayachandran.  Classes for python are not much different than those of other languages  Not much new syntax or semantics  Python classes are.
Lecture 4 Python Basics Part 3.
Python Primer 2: Functions and Control Flow
Topics Introduction to File Input and Output
Python’s Errors and Exceptions
Lecture 4 Python Basics Part 3.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
ERRORS AND EXCEPTIONS Errors:
CSC1018F: Intermediate Python
G. Pullaiah College of Engineering and Technology
Python Syntax Errors and Exceptions
CISC101 Reminders All assignments are now posted.
By Ryan Christen Errors and Exceptions.
CSC 143 Java Errors and Exceptions.
Lecture 7: Python’s Built-in Types and Basic Statements
Topics Introduction to File Input and Output
CISC101 Reminders Assignment 3 due today.
Presentation transcript:

 Name Space ◦ modname.funcname ◦ Main 의 module name: ‘__main__’ if __name__ == ‘__main__’:  Scopes

try: f = open("myfile.txt") except IOError as e: print ‘cannot open:’, e else: for line in f: print line, f.close() finally: # always executed with open("myfile.txt") as f: for line in f: print line, f = open("myfile.txt") for line in f: print line, May raise exception Exception handling Pre-defined Clean-up f always closed!

>>> try:... raise Exception('spam', 'eggs')... except Exception as inst:... print type(inst) # the exception instance... print inst.args # arguments stored in.args... print inst # __str__ allows args to be printed directly... x, y = inst.args... print 'x =', x... print 'y =', y... ('spam', 'eggs') x = spam y = eggs >>> class MyError(Exception):... def __init__(self, value):... self.value = value... def __str__(self):... return repr(self.value)... >>> try:... raise MyError(2*2)... except MyError as e:... print 'My exception occurred, value:', e.value... My exception occurred, value: 4 >>> raise MyError('oops!') Traceback (most recent call last): File " ", line 1, in ? __main__.MyError: 'oops!' See Exception HierarchyException Hierarchy

import logging logging.basicConfig(filename='example.log',level=logging.DEBUG) logging.debug('This message should go to the log file') logging.info('So should this') logging.warning('And this, too') Output: DEBUG:root:This message should go to the log file INFO:root:So should this WARNING:root:And this, too LevelWhen it’s used loggin.debug()DEBUG Detailed information, typically of interest only when diagnosing problems. logging.info()INFOConfirmation that things are working as expected. logging.warning() WARNING (default level) An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. logging.error() logging.exception() ERROR Due to a more serious problem, the software has not been able to perform some function. Only called from exception handler logging.critical()CRITICAL A serious error, indicating that the program itself may be unable to continue running. Main 에서 선언하고 다른 module 에서는 Import 만 high sys.stderr default sys.stderr default

import logging from logging import DEBUG, INFO, WARNING, ERROR def setup_server_logging(name='', logfile='', maxBytes=524288, backupCount=1, level=logging.DEBUG, fmt='%(asctime)s %(name)s %(levelname)s %(message)s'): logger = logging.getLogger('') logger.setLevel(level) ch = logging.handlers.RotatingFileHandler(logfile, maxBytes, backupCount) ch.setLevel(level) formatter = logging.Formatter(fmt) ch.setFormatter(formatter) logger.addHandler(ch) return logger def setup_console_logging(name='', level=logging.DEBUG, fmtt='%(name)s %(levelname)s %(message)s'): """Convenience function for setting up simple logging to console.""" logger = logging.getLogger('') logger.setLevel(level) ch = logging.StreamHandler() ch.setLevel(level) formatter = logging.Formatter(fmt) ch.setFormatter(formatter) logger.addHandler(ch) return logger

>>> import time >>> time.time() >>> time_struct = time.localtime() >>> time_struct time.struct_time(tm_year=2015, tm_mon=5, tm_mday=28, tm_hour=19, tm_min=50, tm_sec=28, tm_wday=3, tm_yday=148, tm_isdst=0) >>> tuple(time_struct) (2015, 5, 28, 19, 50, 28, 3, 148, 0) >>> time.asctime(time_struct) 'Thu May 28 19:50: ' >>> time.gmtime() time.struct_time(tm_year=2015, tm_mon=5, tm_mday=28, tm_hour=10, tm_min=51, tm_sec=13, tm_wday=3, tm_yday=148, tm_isdst=0) >>> begin = time.time(); time.sleep(5); now = time.time() >>> elapsed = now – begin >>> elapsed

Call by Reference Mutable objects passed may be changed

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError('refusenik user') print complaint ask_ok('Do you really want to quit?') ask_ok('OK to overwrite the file?', 2) ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!') # with positional and keyword arguments ask_ok('OK to overwrite the file?', complaint='Come on, only yes or no!’, retries=2)

>>> # *args: arbitrary # of parameters >>> def my_sum(*args): sum = 0 for arg in args: # args: a tuple sum += arg return sum >>> my_sum(1, 2, 3, 4, 5) 15 >>> t = (1, 2, 3, 4, 5) >>> my_sum(t[0], t[1], t[2], t[3], t[4]) 15 >>> my_sum(*t) # unpacking arg list 15 >>> >>> def my_sum(args): # a tuple or list sum = 0 for arg in args: sum += arg return sum >>> t = (1, 2, 3, 4, 5) >>> my_sum(t) 15 >>> my_sum(1, 2, 3, 4, 5) Traceback (most recent call last): File " ", line 1, in my_sum(1,2,3,4,5) TypeError: my_sum() takes exactly 1 argument (5 given) >>>

>>> def cheeseshop(kind, *arguments, **keywords): print "-- Do you have any", kind, "?" print "-- I'm sorry, we're all out of", kind for arg in arguments: print arg print "-" * 40 keys = sorted(keywords.keys()) for kw in keys: print kw, ":", keywords[kw] >>> cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper='Michael Palin', client="John Cleese", sketch="Cheese Shop Sketch") -- Do you have any Limburger ? -- I'm sorry, we're all out of Limburger It's very runny, sir. It's really very, VERY runny, sir client : John Cleese shopkeeper : Michael Palin sketch : Cheese Shop Sketch

# initdata.py # records bob = {'name': 'Bob Smith', 'age': 42, 'pay': 30000, 'job': 'dev'} sue = {'name': 'Sue Jones', 'age': 45, 'pay': 40000, 'job': 'hdw'} tom = {'name': 'Tom', 'age': 50, 'pay': 0, 'job': None} # database db = {} db['bob'] = bob db['sue'] = sue db['tom'] = tom if __name__ == '__main__': # when run as a script for key in db: print key, '=>\n ', db[key]

class Person: def __init__(self, name, age, pay=0, job=None): self.name = name self.age = age self.pay = pay self.job = job def lastName(self): return self.name.split()[-1] def giveRaise(self, percent): self.pay *= (1.0 + percent) class Manager(Person): def __init__(self, name, age, pay): Person.__init__(self, name, age, pay, 'manager') def giveRaise(self, percent, bonus=0.1): Person.giveRaise(self, percent + bonus) if __name__ == '__main__': bob = Person('Bob Smith', 44) sue = Person('Sue Jones', 47, 40000, 'hardware') tom = Manager(name='Tom Doe', age=50, pay=50000) print sue, sue.pay, sue.lastName() for obj in (bob, sue, tom): obj.giveRaise(.10) print obj

 supports most of the same functionality as dictionaries  modified objects are written only when assigned to the shelf  the values (not the keys!) in a shelf can be essentially arbitrary Python objects from initdata import bob, sue import shelve db = shelve.open('people-shelve') db['bob'] = bob db['sue'] = sue db.close() from initdata import tom import shelve db = shelve.open('people-shelve') sue = db['sue'] sue['pay'] *= 1.50 db['sue'] = sue db['tom'] = tom db.close() flagMeaning 'r'Open existing database for reading only 'w'Open existing database for reading and writing 'c'Open database for reading and writing, creating it if it doesn’t exist (default) 'n'Always create a new, empty database, open for reading and writing