 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

Python 3 Some material adapted from Upenn cis391 slides and other sources.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Guide to Programming with Python Chapter Nine Working with/Creating Modules.
Exceptions COMPSCI 105 S Principles of Computer Science.
January 24, 2006And Now For Something Completely Different 1 “And Now For Something Completely Different” A Quick Tutorial of the Python Programming Language.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
Computing Science 1P Large Group Tutorial 17 Simon Gay Department of Computing Science University of Glasgow 2006/07.
Introduction to Python
By Zeng Sheng Liu. os - provides dozens of functions for interacting with the operating system >>> import os >>> os.system('time 0:02') 0 >>> os.getcwd()
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.
By: Joshua O’Donoghue. Operating System Interface In order to interact with the operating system in python you will want to become familiar with the OS.
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
Functions Reading/writing files Catching exceptions
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
Python’s Standard Library - Part I Josh Lawrence.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 6 Value-Returning.
Introduction to Python III CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
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.
Python Functions.
Introduction to OOP OOP = Object-Oriented Programming OOP is very simple in python but also powerful What is an object? data structure, and functions (methods)
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)
An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python
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.
16. Python Files I/O Printing to the Screen: The simplest way to produce output is using the print statement where you can pass zero or more expressions,
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!.
 Name Space ◦ modname.funcname ◦ Main 의 module name: ‘__main__’ if __name__ == ‘__main__’:  Scopes.
Python’s Standard Library Part I Joe Houpert CS265.
PC204 Lecture 5 Conrad Huang Genentech Hall, N453A
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.
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.
By: Aradhya Malhotra.  To interact with the OS in python you will want to become familiar with the OS module  The command “import os” is used for this.
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.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Tips. Iteration On a list: o group = ["Paul","Duncan","Jessica"] for person in group: print(group) On a dictionary: o stock = {'eggs':15, 'milk':3, 'sugar':28}
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.
CHAPTER FOUR Functions.
Python Primer 2: Functions and Control Flow
Topics Introduction to File Input and Output
Introduction To Python
Python’s Errors and Exceptions
Winter 2018 CISC101 12/1/2018 CISC101 Reminders
Lecture 4 Python Basics Part 3.
ERRORS AND EXCEPTIONS Errors:
CSC1018F: Intermediate Python
G. Pullaiah College of Engineering and Technology
By Ryan Christen Errors and Exceptions.
Lecture 7: Python’s Built-in Types and Basic Statements
Topics Introduction to File Input and Output
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

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

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.ctime() 'Sat May 30 00:11: ' >>> 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: ' >>> begin = time.time(); time.sleep(5); now = time.time() >>> elapsed = now – begin >>> elapsed

>>> import os >>> os.getcwd() # Return the current working directory 'C:\\Python27‘ >>> os.listdir(‘.’) ['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'Scripts', 'tcl', 'Tools', 'w9xpopen.exe'] >>> os.chdir(‘Lib’) # Change current working directory >>> os.path.split(os.getcwd()) ('C:\\Python27', 'Lib') >>> os.mkdir(‘tmp’) >>> os.system(‘dir') # Run the command mkdir in the system shell 0 >>>

>>> import math >>> math.cos(math.pi / 4.0) >>> math.log(1024, 2) 10.0 >>> import random >>> random.choice(['apple', 'pear', 'banana']) 'apple' >>> random.sample(xrange(100), 10) # sampling without replacement [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] >>> random.random() # random float >>> random.randrange(6) # random integer chosen from range(6) 4