Extra Stuff for CS106 Victor Norman CS106. break and continue break and continue are both ways to alter the flow of a loop Can be used only inside a loop.

Slides:



Advertisements
Similar presentations
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Advertisements

Introduction to C Programming
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Introduction to Python
Strings Victor Norman CS104 Calvin College. Reading Quiz Counts toward your grade.
Introduction to C Programming
Fundamentals of Python: From First Programs Through Data Structures
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Guide to Programming with Python Chapter Nine Working with/Creating Modules.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
“Everything Else”. Find all substrings We’ve learned how to find the first location of a string in another string with find. What about finding all matches?
Line Continuation, Output Formatting, and Decision Structures CS303E: Elements of Computers and Programming.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
General Programming Introduction to Computing Science and Programming I.
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
If statements while loop for loop
Files Victor Norman CS104. Reading Quiz, Q1 A file must be ___________ before a program can read data from it. A. accessed B. unlocked C. opened D. controlled.
Built-in Data Structures in Python An Introduction.
Chapter 3: Formatted Input/Output Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Python Functions.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
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.
Last Week Modules Save functions to a file, e.g., filename.py The file filename.py is a module We can use the functions in filename.py by importing it.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Python Let’s get started!.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
Classes and Objects, Part 1 Victor Norman CS104. “Records” In Excel, you can create rows that represent individual things, with each column representing.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
Lists Victor Norman CS104. Reading Quiz Lists Our second collection data type – elements are in order (like strings) – indexed from 0 to n – 1 (like.
Q and A for Sections 6.2, 6.3 Victor Norman CS106.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
More about Iteration Victor Norman CS104. Reading Quiz.
Introduction to Python
Line Continuation, Output Formatting, and Decision Structures
Containers and Lists CIS 40 – Introduction to Programming in Python
CS-104 Final Exam Review Victor Norman.
Functions CIS 40 – Introduction to Programming in Python
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Line Continuation, Output Formatting, and Decision Structures
Topics Introduction to File Input and Output
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Winter 2018 CISC101 12/1/2018 CISC101 Reminders
CISC101 Reminders Assn 3 due tomorrow, 7pm.
ERRORS AND EXCEPTIONS Errors:
Introduction to Python: Day Three
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Python programming exercise
CISC101 Reminders All assignments are now posted.
EECE.2160 ECE Application Programming
Introduction to Computer Science
“Everything Else”.
Topics Introduction to File Input and Output
CISC101 Reminders Assignment 3 due today.
Presentation transcript:

Extra Stuff for CS106 Victor Norman CS106

break and continue break and continue are both ways to alter the flow of a loop Can be used only inside a loop – for loop or while loop.

break Exits the loop immediately Control jumps to the next statement after the loop. Only exits the loop it is in. – not an outer loop. Very useful if search for something and have found it – no need to go on searching.

break Example Searching for val in list nums : found = False for num in nums: if num == i: found = True break if found: print “Found”, val else: print val, “is not in the list.”

continue Control jumps back up to top of loop immediately. Very useful if you have a large body of statement in a loop and know you don’t want to run any more code for that time through the loop – E.g., very useful for filtering out data you are not interested in.

continue Example Filtering out items you don’t need to deal with: only want to handle lines from a file that do not start with # and are not blank lines. for line in datafile: if line.startswith(“#”): continue if line.strip() == “”: continue # 300 lines of code here to deal with # good lines of data

Formatted Output Found in section 8.2. Problem: using just print it is very hard, if not impossible to get your output to show up just how you want it. – how to print floats with 3 digits behind the decimal? – how to print a string in a “field width” of 20. – etc.

Example class Team """Represents a baseball team""" def __init__(self, name, wins, losses): self._name = name self._wins = wins self._losses = losses # add getters, etc. here. # Create a list of 4 teams teams = [ Team("Pirates", 120, 42), Team("Tigers", 105, 57), Team("Yankees", 30, 132), Team("Diamondbacks", 81, 81) ]

Example (2) How would we print out the four teams in a nice table, with 20 spaces for the team name, left-justified, 4 spaces for wins column, 4 for losses, etc.?

Solution: use formatted output the % operator, on strings, is the format operator (not mod operator). Syntax: – spec-string % (tuple of values) if there is only one value, it does not have to be in a tuple – produces a string as a result – spec-string is a string containing multiple specifications, one per number of values in tuple. – i.e., if the tuple contains 3 items, there has to be 3 specifications in the spec-string. – n-th item in the tuple uses the n-th specification in the spec-string.

Example n = 1 cheese = “Mozzarella” weight = print “%d. Width of %s is %8.3f kilograms.” % (n, cheese, weight) Output: 1. Weight of Mozzarella is kilograms.

Specifications in spec-string Any character that is not a specification is reproduced unchanged in the result. Specifications: – %d: replace with given integer – %s: replace with given string – %f: replace with given float – %: put % in the output.

Exercise Write a print statement that prints this out: Hello, my name is. where is in a variable name. Could do this: print “Hello, my name is ” + name + “.” Or, use %s. Answer: print “Hello, my name is %s.” % name

Exercise 2 Write the code to print out: 0. Cheddar 1.Venezuelan Beaver Cheese 2.Roquefort when given a list of strings cheeses. Use %d for the number at the beginning. Answer: for i in range(len(cheeses)): print “%d. %s” % (i, cheeses[i])

More details You can specify the field width and # digits behind a decimal, justification, etc. %. f – %8.3f: put the float in a field of 8, with 3 digits behind decimal point. Round it. Right justified. – decimal point takes up one “space”. % s: right-justified string in the given field width % d: similar to string.

Examples print “%8.3f.*” % * print “%-8.3f*” % * (left justified, 3 spaces trail) print “%-20s:” % “Pirates” Pirates : print “%-20s:” % “Diamondbacks” Diamondbacks :

Error Handling Big Question: What should a function do when it cannot do its work because of bad input? E.g., def avg(items): return sum(items) / len(items) What bad inputs might we need to handle?

Option 1 def avg(items): if len(items) == 0: return "No items to average" else: return sum(items) / len(items) res = avg(myItems) if res == “No items to average”: do_something() else: do_something_else() Still doesn’t handle a list like this: [“hi”, “there”] Still doesn’t handle a list like this: [“hi”, “there”]

Another example You provide a nice Card class. Someone tries to use it this way: myCard = Card(87, “P”) Should your code create this card? If so, it won’t be able to print it, and might not work for other stuff… What should it do instead? (Constructors don’t return anything.)

Solution: Exceptions! Used to report unusual or error condition from a function/method back to the caller. Terminology: – an exception is raised or thrown in a function/method when the error condition is detected. e.g., ZeroDivisionError. – an exception can be caught or handled by the caller, or allowed to propagate up to the caller’s caller.

Syntax to catch an exception try: except : (Lots of other parts available to this too, like else, finally, etc.)

Another Example Want code to read in a number from the user, and make sure it is a good number… while True: try: x = float(raw_input(“Enter a number: “)) break except ValueError: print “That was not a number!”

Raising an exception You can throw/raise an exception explicitly in your code, e.g., when you get bad input: class Card: def __init__(self, denom, suit): if suit not in (‘C’, ‘D’, ‘H’, ‘S’): raise ValueError(“suit must be one of C, D, H, or S”) self._suit = suit self._denom = denom What else should we check?

Full Code class Card: def __init__(self, denom, suit): if not isinstance(denom, int): raise TypeError(“denom must be an int”) if denom not in range(2, 15): raise ValueError(“denom must have value 2 to 14”) if not isinstance(suit, str): raise TypeError(“suit must be a string.”) if suit not in (‘C’, ‘D’, ‘H’, ‘S’): raise ValueError(“suit must be one of C, D, H, or S”) # code here to store denom, suit, etc. NOTE: now, when you have a Card object, you *know* it has good state.

Pre-defined Exceptions/Errors html#exception-hierarchy html#exception-hierarchy Exercise: fix the avg() call to raise appropriate exceptions.

PYTHONPATH, etc. Q: Where does python look when import ing modules? A: The python interpreter looks at the environment variable PYTHONPATH, which is a list of directories. It looks in each directory for the name of the module, and when found, loads it. Can see this PATH from within python…

sys.path To see the python path, start up python and do this: >>> import sys >>> print sys.path ['', '//anaconda/lib/python27.zip', '//anaconda/lib/python2.7', '//anaconda/lib/python2.7/plat-darwin', '//anaconda/lib/python2.7/plat- mac', '//anaconda/lib/python2.7/plat-mac/lib-scriptpackages', '//anaconda/lib/python2.7/lib-tk', '//anaconda/lib/python2.7/lib-old', '//anaconda/lib/python2.7/lib-dynload', '//anaconda/lib/python2.7/site- packages', '//anaconda/lib/python2.7/site-packages/Sphinx py2.7.egg', '//anaconda/lib/python2.7/site-packages/aeosa', '//anaconda/lib/python2.7/site-packages/setuptools py2.7.egg']

pep8 A “pep” is a Python Enhancement Proposal. Documents recording how the language evolves – new features, new releases, suggestions, etc. PEP-8 is the style guide You can run your code “through” pep8 to get feedback on how well it conforms.

Example Mac52078:distrib_yourself vtn2$ pep8 main.py main.py:20:80: E501 line too long (85 > 79 characters) main.py:21:80: E501 line too long (90 > 79 characters) main.py:23:80: E501 line too long (89 > 79 characters) main.py:25:80: E501 line too long (83 > 79 characters) main.py:26:80: E501 line too long (89 > 79 characters) main.py:30:80: E501 line too long (91 > 79 characters) main.py:38:80: E501 line too long (88 > 79 characters) main.py:47:1: E303 too many blank lines (3) main.py:51:1: E302 expected 2 blank lines, found 1 main.py:69:1: W293 blank line contains whitespace main.py:110:1: W293 blank line contains whitespace main.py:124:80: E501 line too long (85 > 79 characters) main.py:155:5: E301 expected 1 blank line, found 0 main.py:157:5: E301 expected 1 blank line, found 0 main.py:159:5: E301 expected 1 blank line, found 0 main.py:161:5: E301 expected 1 blank line, found 0 main.py:186:80: E501 line too long (83 > 79 characters) main.py:187:80: E501 line too long (90 > 79 characters) main.py:201:1: W293 blank line contains whitespace main.py:224:9: E303 too many blank lines (2) main.py:230:1: E302 expected 2 blank lines, found 1 main.py:269:1: W391 blank line at end of file

Dictionary intro Big Question: How would you store the information in a phone book in a data structure in python? Phone book maps names to : phone numbers addresses

Ideas? A class that stores all info (phone #, name, address) and is stored in a list, sorted by name? Q: What operations do you need to do? How fast should they be? Q: Why is the data ordered in a phone book?

Dictionaries, in python type: dict one-way mappings, from “keys”  “values”. – keys must be immutable. – any value can be stored. each mapping is called an “entry”. unordered. Compared to list?: – list: ordered mapping of consecutive integers to values. mutable data structure

dict Operations Creation: d = dict() or d = {} d = { ‘a’: 3, ‘b’: ‘hello’, 33: 77, (3, 4): [‘sword’, ‘potion’]} (newlines above just for readability)

Lookup / Testing d[k] : gets value for key k. Error if k not a key in d. len(d): returns # of entries in d. d.keys(): list of keys in d. if k in d: test if key k is in dictionary d. for k in d: d.items() returns list of tuples of (key, value) pairs.

Insertion d[k] = v : add entry k  v to dict d. if entry with key k exists already, replaces value with v.

Example: count bases bases = { ‘A’: 0, ‘G’: 0, ‘T’: 0, ‘C’: 0} genome = “ATCGGGTCAAAAACCCTTGAGAGAG” for base in bases: bases[base] += 1

Example # dictionary has one word per line. f = open(“dictionary.txt”) # map word length to list of words. wordsByLenDict = {} for w in f.readline(): w = w.strip() # remove newline, spaces. lenw = len(w) if lenw in wordsByLenDict: wordsByLenDict[lenw].append(w) wordsByLenDict[lenw].sort() else: # Add new entry mapping len to list of # words, containing only w at this time. wordsByLenDict[lenw] = [w]

Use the dictionary print all two letter words, one word per line if 2 in wordsByLenDict: # 2 is the key for w in wordsByLenDict[2]: print w print all words, sorted by length. keys = wordsByLenDict.keys() keys.sort() for k in keys: for w in wordsByLenDict[k]: print w

Summary: characteristics of dict Very fast insertion Very fast look-up. Keys much be unique and immutable. – One-to-one or one-to-many relationship. Values can be anything. Unordered.

Consider the following… Consider this definition: class Card: def __init__(self, denom, suit): legal_nums = range(2, 15) legal_suits = (‘C’, ‘H’, ‘S’, ‘D’) if denom not in legal_nums: raise ValueError(“Bad #”) if suit not in legal_suits: raise ValueError(“Bad suit”) Every instance of Card has legal_nums and legal_suits defined during instantiation. (Create 1000 full decks and you create legal_nums and legal_suits, all exactly the same.)

Class Variables legal_nums and legal_suits are not dependent on the values passed in to the constructor… We could make them global… Yuck. Make them class variables. They exist in the class only, not in each object.

Solution class Card: legal_nums = range(2, 15) legal_suits = (‘C’, ‘H’, ‘S’, ‘D’) def __init__(self, denom, suit): if denom not in Card.legal_nums: raise ValueError(“Bad #”) if suit not in Card.legal_suits: raise ValueError(“Bad suit”) # could also reference them via self.

Gotchas Consider this: class C: c = 3 def __init__(self): print self.c C.c = 33 print self.c self.c = 77 print C.c print self.c c = C() Output: