Introduction to Computing Using Python Dictionary container class + modules  Container Class dict  Modules, revisited.

Slides:



Advertisements
Similar presentations
Container Types in Python
Advertisements

15. Python - Modules A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand.
Setting the PYTHONPATH PYTHONPATH is where Python looks for modules it is told to import List of paths Add new path to the end with: setenv PYTHONPATH.
Perkovic, Chapter 7 Functions revisited Python Namespaces
Dictionaries: Keeping track of pairs
Introduction to Computing Using Python Namespaces and Exceptions, revisited  Encapsulation in Functions  Global versus Local Namespaces  Exceptional.
Introduction to Computing Using Python Imperative Programming  Python Programs  Interactive Input/Output  One-Way and Two-Way if Statements  for Loops.
Programming for Engineers in Python
Python Dictionary.
COMPSCI 101 Principles of Programming Lecture 24 – Using dictionaries to manage a small file of information.
Concepts when Python retrieves a variable’s value Namespaces – Namespaces store information about identifiers and the values to which they are bound –
 2002 Prentice Hall. All rights reserved. 1 Chapter 4 – Control Structures Outline 4.1 Introduction 4.2 Program Components in Python 4.3 Functions 4.4Module.
 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.
Introduction to Python. Outline Python IS ……. History Installation Data Structures Flow of Control Functions Modules References.
FORTRAN.  Fortran or FORmula TRANslation was developed in the 1950's by IBM as an alternative to Assembly Language. First successfull high level language.
1 Python Chapter 2 © Samuel Marateck, After you install the compiler, an icon labeled IDLE (Python GUI) will appear on the screen. If you click.
Writing Solid Code Introduction to Python. Program 1 python -c "print 'Hello World' “ python -c "import time; print time.asctime()“ Start an interactive.
Introduction to Computing Using Python More Built-in Container Classes  Container Class dict  Encoding of String Characters  Randomness and Random Sampling.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Introduction to Computing Using Python More Built-in Container Classes  Container Class dict  Container Class set  Container Class tuple  Encoding.
CSC 110 Numeric data types [Reading: chapter 3] CSC 110 D 1.
CS 100: Roadmap to Computing Fall 2014 Lecture 01.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
1 TAC2000/ Protocol Engineering and Application Research Laboratory (PEARL) MATH Functions in C Language.
Sorting and Modules. Sorting Lists have a sort method >>> L1 = ["this", "is", "a", "list", "of", "words"] >>> print L1 ['this', 'is', 'a', 'list', 'of',
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
H3D API Training  Part 3.1: Python – Quick overview.
Modules and Decomposition UW CSE 190p Summer 2012 download examples from the calendar.
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Introduction to Computing Using Python Straight-line code  In chapter 2, code was “straight-line”; the Python statements in a file (or entered into the.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
Built-in Data Structures in Python An Introduction.
Libraries Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
MA/CS 375 Fall 2002 Lecture 3. Example 2 A is a matrix with 3 rows and 2 columns.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
Tuples Chapter 10 Python for Informatics: Exploring Information
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.
MA/CS 375 Fall 2003 Lecture 3. .* Multiplication We can use the.* operator to perform multiplication entry by entry of two matrices:
14. DICTIONARIES AND SETS Rocky K. C. Chang 17 November 2014 (Based on from Charles Dierbach, Introduction to Computer Science Using Python and Punch and.
Introduction to Computing Using Python Dictionaries: Keeping track of pairs  Class dict  Class tuple.
MA/CS 375 Fall 2002 Lecture 2. Motivation for Suffering All This Math and Stuff Try the Actor demo from
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.
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
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 Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
Introduction to Python Developed by Dutch programmer Guido van Rossum Named after Monty Python Open source development project Simple, readable language.
Python I/O Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Classic file reading 1 infile = open(’filename.txt’, ’r’) for line.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
A Python programming class for you
G. Pullaiah College of Engineering and Technology
CS 100: Roadmap to Computing
CSc 120 Introduction to Computer Programing II
Object-Oriented Programming
Topics Introduction to File Input and Output
Ruth Anderson University of Washington CSE 160 Spring 2018
CS 1111 Introduction to Programming Fall 2018
Rocky K. C. Chang 15 November 2018 (Based on Dierbach)
6. Dictionaries and sets Rocky K. C. Chang 18 October 2018
CHAPTER 3: String And Numeric Data In Python
Dictionaries: Keeping track of pairs
CHAPTER 4: Lists, Tuples and Dictionaries
Terminal-Based Programs
CS 100: Roadmap to Computing
Topics Introduction to File Input and Output
Presentation transcript:

Introduction to Computing Using Python Dictionary container class + modules  Container Class dict  Modules, revisited

Introduction to Computing Using Python User-defined indexes and dictionaries >>> employee[ ] ['Yu', 'Tsun'] >>> employee[ ] ['Anna', 'Karenina'] >>> employee[ ] ['Hans', 'Castorp'] >>> employee[ ] ['Yu', 'Tsun'] >>> employee[ ] ['Anna', 'Karenina'] >>> employee[ ] ['Hans', 'Castorp'] Goal: a container of employee records indexed by employee SS# Problems: the range of SS#s is huge SS#s are not really integers Solution: the dictionary class dict >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> A dictionary contains (key, value) pairs >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee[' '] ['Yu', 'Tsun'] >>> employee[' '] ['Anna', 'Karenina'] >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee[' '] ['Yu', 'Tsun'] >>> employee[' '] ['Anna', 'Karenina'] keyvalue ' '['Anna', 'Karenina'] ' '['Yu', 'Tsun'] ' '['Hans', 'Castorp'] A key can be used as an index to access the corresponding value

Introduction to Computing Using Python Properties of dictionaries >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun']} >>> >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun']} >>> Dictionaries are not ordered Dictionaries are mutable >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun']} >>> employee[' '] = 'Holden Cafield' >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': 'Holden Cafield'} >>> >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun']} >>> employee[' '] = 'Holden Cafield' >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': 'Holden Cafield'} >>> >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun']} >>> employee[' '] = 'Holden Cafield' >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': 'Holden Cafield'} >>> employee[' '] = 'Holden Caulfield' >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': 'Holden Caulfield’} >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun']} >>> employee[' '] = 'Holden Cafield' >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': 'Holden Cafield'} >>> employee[' '] = 'Holden Caulfield' >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': 'Holden Caulfield’} Dictionaries are mutable new (key,value) pairs can be added Dictionaries are mutable new (key,value) pairs can be added the value corresponding to a key can be modified The empty dictionary is {} Dictionary keys must be immutable >>> employee = {[1,2]:1, [2,3]:3} Traceback (most recent call last): File " ", line 1, in employee = {[1,2]:1, [2,3]:3} TypeError: unhashable type: 'list' >>> employee = {[1,2]:1, [2,3]:3} Traceback (most recent call last): File " ", line 1, in employee = {[1,2]:1, [2,3]:3} TypeError: unhashable type: 'list'

Introduction to Computing Using Python Dictionary operators >>> days = {'Mo':1, 'Tu':2, 'W':3} >>> days['Mo'] 1 >>> days['Th'] = 5 >>> days {'Mo': 1, 'Tu': 2, 'Th': 5, 'W': 3} >>> days['Th'] = 4 >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> 'Fr' in days False >>> len(days) 4 >>> days = {'Mo':1, 'Tu':2, 'W':3} >>> days['Mo'] 1 >>> days['Th'] = 5 >>> days {'Mo': 1, 'Tu': 2, 'Th': 5, 'W': 3} >>> days['Th'] = 4 >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> 'Fr' in days False >>> len(days) 4 Class dict supports some of the same operators as class list Class dict does not support all the operators that class list supports + and * for example

Introduction to Computing Using Python Dictionary methods >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> days.pop('Tu') 2 >>> days {'Mo': 1, 'Th': 4, 'W': 3} >>> days2 = {'Tu':2, 'Fr':5} >>> days.update(days2) >>> days {'Fr': 5, 'W': 3, 'Th': 4, 'Mo': 1, 'Tu': 2} >>> days.items() dict_items([('Fr', 5), ('W', 3), ('Th', 4), ('Mo', 1), ('Tu', 2)]) >>> days.keys() dict_keys(['Fr', 'W', 'Th', 'Mo', 'Tu']) >>> >>> vals = days.values() >>> vals dict_values([5, 3, 4, 1, 2]) >>> >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> days.pop('Tu') 2 >>> days {'Mo': 1, 'Th': 4, 'W': 3} >>> days2 = {'Tu':2, 'Fr':5} >>> days.update(days2) >>> days {'Fr': 5, 'W': 3, 'Th': 4, 'Mo': 1, 'Tu': 2} >>> days.items() dict_items([('Fr', 5), ('W', 3), ('Th', 4), ('Mo', 1), ('Tu', 2)]) >>> days.keys() dict_keys(['Fr', 'W', 'Th', 'Mo', 'Tu']) >>> >>> vals = days.values() >>> vals dict_values([5, 3, 4, 1, 2]) >>> OperationExplanation d.items() Returns a view of the (key, value) pairs in d d.keys() Returns a view of the keys of d d.pop(key) Removes the (key, value) pair with key key from d and returns the value d.update(d2) Adds the (key, value) pairs of dictionary d2 to d d.values() Returns a view of the values of d The containers returned by d.items(), d.keys(), and d.values() (called views) can be iterated over >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> days.pop('Tu') 2 >>> days {'Mo': 1, 'Th': 4, 'W': 3} >>> days2 = {'Tu':2, 'Fr':5} >>> days.update(days2) >>> days {'Fr': 5, 'W': 3, 'Th': 4, 'Mo': 1, 'Tu': 2} >>> days.items() dict_items([('Fr', 5), ('W', 3), ('Th', 4), ('Mo', 1), ('Tu', 2)]) >>> days.keys() dict_keys(['Fr', 'W', 'Th', 'Mo', 'Tu']) >>> >>> vals = days.values() >>> vals dict_values([5, 3, 4, 1, 2]) >>> for val in vals: print(val, end=' ') >>> >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> days.pop('Tu') 2 >>> days {'Mo': 1, 'Th': 4, 'W': 3} >>> days2 = {'Tu':2, 'Fr':5} >>> days.update(days2) >>> days {'Fr': 5, 'W': 3, 'Th': 4, 'Mo': 1, 'Tu': 2} >>> days.items() dict_items([('Fr', 5), ('W', 3), ('Th', 4), ('Mo', 1), ('Tu', 2)]) >>> days.keys() dict_keys(['Fr', 'W', 'Th', 'Mo', 'Tu']) >>> >>> vals = days.values() >>> vals dict_values([5, 3, 4, 1, 2]) >>> for val in vals: print(val, end=' ') >>>

Introduction to Computing Using Python Dictionary vs. multi-way if statement Uses of a dictionary: container with custom indexes def complete(abbreviation): 'returns day of the week corresponding to abbreviation' if abbreviation == 'Mo': return 'Monday' elif abbreviation == 'Tu': return 'Tuesday' elif else: # abbreviation must be Su return 'Sunday' def complete(abbreviation): 'returns day of the week corresponding to abbreviation' if abbreviation == 'Mo': return 'Monday' elif abbreviation == 'Tu': return 'Tuesday' elif else: # abbreviation must be Su return 'Sunday' def complete(abbreviation): 'returns day of the week corresponding to abbreviation' days = {'Mo': 'Monday', 'Tu':'Tuesday', 'We': 'Wednesday', 'Th': 'Thursday', 'Fr': 'Friday', 'Sa': 'Saturday', 'Su':'Sunday'} return days[abbreviation] def complete(abbreviation): 'returns day of the week corresponding to abbreviation' days = {'Mo': 'Monday', 'Tu':'Tuesday', 'We': 'Wednesday', 'Th': 'Thursday', 'Fr': 'Friday', 'Sa': 'Saturday', 'Su':'Sunday'} return days[abbreviation] Uses of a dictionary: container with custom indexes alternative to the multi-way if statement

Introduction to Computing Using Python Dictionary as a container of counters >>> grades = [95, 96, 100, 85, 95, 90, 95, 100, 100] >>> frequency(grades) {96: 1, 90: 1, 100: 3, 85: 1, 95: 3} >>> >>> grades = [95, 96, 100, 85, 95, 90, 95, 100, 100] >>> frequency(grades) {96: 1, 90: 1, 100: 3, 85: 1, 95: 3} >>> Problem: computing the number of occurrences of items in a list Solution: Iterate through the list and, for each grade, increment the counter corresponding to the grade. Problems: impossible to create counters before seeing what’s in the list how to store grade counters so a counter is accessible using the corresponding grade Solution: a dictionary mapping a grade (the key) to its counter (the value) Uses of a dictionary: container with custom indexes alternative to the multi-way if statement container of counters

Introduction to Computing Using Python Dictionary as a container of counters >>> grades = [95, 96, 100, 85, 95, 90, 95, 100, 100] Problem: computing the number of occurrences of items in a list 95 1 def frequency(itemList): 'returns frequency of items in itemList' counters = {} def frequency(itemList): 'returns frequency of items in itemList' counters = {} ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ counters def frequency(itemList): 'returns frequency of items in itemList' counters = {} for item in itemList: if item in counters: # increment item counter counters[item] += 1 else: # create item counter counters[item] = 1 return counters def frequency(itemList): 'returns frequency of items in itemList' counters = {} for item in itemList: if item in counters: # increment item counter counters[item] += 1 else: # create item counter counters[item] = 1 return counters

Introduction to Computing Using Python Exercise def numChars(filename): 'returns the number of characters in file filename' infile = open(filename, 'r') content = infile.read() infile.close() return len(content) def numChars(filename): 'returns the number of characters in file filename' infile = open(filename, 'r') content = infile.read() infile.close() return len(content) Implement function wordcount() that takes as input a text—as a string— and prints the frequency of each word in the text; assume there is no punctuation in the text. def wordCount(text): 'prints frequency of each word in text' wordList = text.split() # split text into list of words counters ={} # dictionary of counters for word in wordList: if word in counters: # counter for word exists counters[word] += 1 else: # counter for word doesn't exist counters[word] = 1 for word in counters: # print word counts if counters[word] == 1: print('{:8} appears {} time.'.format(word, counters[word])) else: print('{:8} appears {} times.'.format(word, counters[word])) def wordCount(text): 'prints frequency of each word in text' wordList = text.split() # split text into list of words counters ={} # dictionary of counters for word in wordList: if word in counters: # counter for word exists counters[word] += 1 else: # counter for word doesn't exist counters[word] = 1 for word in counters: # print word counts if counters[word] == 1: print('{:8} appears {} time.'.format(word, counters[word])) else: print('{:8} appears {} times.'.format(word, counters[word])) >>> text = 'all animals are equal but some animals are more equal than other' >>> wordCount(text) all appears 1 time. animals appears 2 times. some appears 1 time. equal appears 2 times. but appears 1 time. other appears 1 time. are appears 2 times. than appears 1 time. more appears 1 time. >>> >>> text = 'all animals are equal but some animals are more equal than other' >>> wordCount(text) all appears 1 time. animals appears 2 times. some appears 1 time. equal appears 2 times. but appears 1 time. other appears 1 time. are appears 2 times. than appears 1 time. more appears 1 time. >>>

Introduction to Computing Using Python Built-in class tuple >>> lst = ['one', 'two', 3] >>> lst[2] 3 >>> lst[2] = 'three' >>> lst ['one', 'two', 'three'] >>> tpl = ('one', 'two', 3) >>> tpl ('one', 'two', 3) >>> tpl[2] 3 >>> tpl[2] = 'three' Traceback (most recent call last): File " ", line 1, in tpl[2] = 'three' TypeError: 'tuple' object does not support item assignment >>> >>> lst = ['one', 'two', 3] >>> lst[2] 3 >>> lst[2] = 'three' >>> lst ['one', 'two', 'three'] >>> tpl = ('one', 'two', 3) >>> tpl ('one', 'two', 3) >>> tpl[2] 3 >>> tpl[2] = 'three' Traceback (most recent call last): File " ", line 1, in tpl[2] = 'three' TypeError: 'tuple' object does not support item assignment >>> The class tuple is the same as class list … except that it is immutable Why do we need it?Why do we need it? Sometimes, we need to have an “immutable list”. For example, when we need a dictionary that has lists as keys

Introduction to Computing Using Python Exercise Implement function lookup() that implements a phone book lookup application. Your function takes, as input, a dictionary representing a phone book, mappingtuples (containing the first and last name) to strings (containing phone numbers) def lookup(phonebook): '''implements interactive phone book service using the input phonebook dictionary''' while True: first = input('Enter the first name: ') last = input('Enter the last name: ') person = (first, last) # construct the key if person in phonebook: # if key is in dictionary print(phonebook[person]) # print value else: # if key not in dictionary print('The name you entered is not known.') def lookup(phonebook): '''implements interactive phone book service using the input phonebook dictionary''' while True: first = input('Enter the first name: ') last = input('Enter the last name: ') person = (first, last) # construct the key if person in phonebook: # if key is in dictionary print(phonebook[person]) # print value else: # if key not in dictionary print('The name you entered is not known.') >>> phonebook = { ('Anna','Karenina'):'(123) ', ('Yu', 'Tsun'):'(901) ', ('Hans', 'Castorp'):'(321) '} >>> lookup(phonebook) Enter the first name: Anna Enter the last name: Karenina (123) Enter the first name: >>> phonebook = { ('Anna','Karenina'):'(123) ', ('Yu', 'Tsun'):'(901) ', ('Hans', 'Castorp'):'(321) '} >>> lookup(phonebook) Enter the first name: Anna Enter the last name: Karenina (123) Enter the first name:

>>> import math >>> >>> import math >>> >>> import math >>> dir(math) ['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc’] >>> >>> import math >>> dir(math) ['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc’] >>> >>> import math >>> dir(math) ['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc’] >>> math.sqrt >>> math.pi >>> import math >>> dir(math) ['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc’] >>> math.sqrt >>> math.pi Introduction to Computing Using Python Modules, revisited When the module is executed (imported), then the module is (also) a namespace. A module is a file containing Python code. When the module is executed (imported), then the module is (also) a namespace. This namespace has a name, typically the name of the module. When the module is executed (imported), then the module is (also) a namespace. This namespace has a name, typically the name of the module. In this namespace live the names that are defined in the global scope of the module: the names of functions, values, and classes defined in the module. These names are the module’s attributes. When the module is executed (imported), then the module is (also) a namespace. This namespace has a name, typically the name of the module. In this namespace live the names that are defined in the global scope of the module: the names of functions, values, and classes defined in the module. Built-in function dir() returns the names defined in a namespace To access the imported module’s attributes, the name of the namespace must be specified

Introduction to Computing Using Python Importing a module When the Python interpreter executes an import statement, it: 1.Looks for the file corresponding to the module to be imported. 2.Runs the module’s code to create the objects defined in the module. 3.Creates a namespace where the names of these objects will live. An import statement only lists a name, the name of the module without any directory information or.py suffix. Python uses the Python search path to locate the module. The search path is a list of directories where Python looks for modules. The variable name path defined in the Standard Library module sys refers to this list. When the Python interpreter executes an import statement, it: 1.Looks for the file corresponding to the module to be imported. >>> import sys >>> sys.path ['/Users/me', '/Library/Frameworks/Python.framework/Versions/3.2/lib/python32.zip',... '/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages'] >>> >>> import sys >>> sys.path ['/Users/me', '/Library/Frameworks/Python.framework/Versions/3.2/lib/python32.zip',... '/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages'] >>> current working directoryStandard Library folders

>>> ================ RESTART ================ >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> import example Traceback (most recent call last): File " ", line 1, in import example ImportError: No module named example >>> >>> ================ RESTART ================ >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> import example Traceback (most recent call last): File " ", line 1, in import example ImportError: No module named example >>> >>> ================ RESTART ================ >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> >>> ================ RESTART ================ >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> Introduction to Computing Using Python The Python search path Suppose we want to import module example stored in folder /Users/me that is not in list sys.path >>> ================ RESTART ================ >>> >>> ================ RESTART ================ >>> >>> ================ RESTART ================ >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> import example Traceback (most recent call last): File " ", line 1, in import example ImportError: No module named example >>> import sys >>> sys.path.append('/Users/me') >>> import example >>> example.f >>> example.x 0 >>> >>> ================ RESTART ================ >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> import example Traceback (most recent call last): File " ", line 1, in import example ImportError: No module named example >>> import sys >>> sys.path.append('/Users/me') >>> import example >>> example.f >>> example.x 0 >>> >>> ================ RESTART ================ >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> import example Traceback (most recent call last): File " ", line 1, in import example ImportError: No module named example >>> import sys >>> sys.path.append('/Users/me') >>> import example >>> example.f >>> example.x 0 >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'example', 'sys’] >>> ================ RESTART ================ >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> import example Traceback (most recent call last): File " ", line 1, in import example ImportError: No module named example >>> import sys >>> sys.path.append('/Users/me') >>> import example >>> example.f >>> example.x 0 >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'example', 'sys’] By just adding folder /Users/me to the search path, module example can be imported When called without an argument, function dir() returns the names in the top-level module the shell, in this case. 'an example module' def f(): 'function f' print('Executing f()') def g(): 'function g' print('Executing g()') x = 0 # global var 'an example module' def f(): 'function f' print('Executing f()') def g(): 'function g' print('Executing g()') x = 0 # global var names in the shell namespace; note that example is not in no folder in the Python search path contains module example

Introduction to Computing Using Python Three ways to import module attributes 'an example module' def f(): 'function f' print('Executing f()') def g(): 'function g' print('Executing g()') x = 0 # global var 'an example module' def f(): 'function f' print('Executing f()') def g(): 'function g' print('Executing g()') x = 0 # global var example.py namespace __main__ >>> f module example example f() 0 0 gx g() 1. Import the (name of the) module >>> import example >>> >>> import example >>> >>> import example >>> example.x 0 >>> example.f >>> example.f() Executing f() >>> >>> import example >>> example.x 0 >>> example.f >>> example.f() Executing f() >>>

Introduction to Computing Using Python Three ways to import module attributes 'an example module' def f(): 'function f' print('Executing f()') def g(): 'function g' print('Executing g()') x = 0 # global var 'an example module' def f(): 'function f' print('Executing f()') def g(): 'function g' print('Executing g()') x = 0 # global var example.py namespace __main__ >>> f module example f f() 0 0 gx g() 2. Import specific module attributes >>> from example import f >>> >>> from example import f >>> >>> from example import f >>> f() Executing f() >>> x Traceback (most recent call last): File " ", line 1, in x NameError: name 'x' is not defined >>> >>> from example import f >>> f() Executing f() >>> x Traceback (most recent call last): File " ", line 1, in x NameError: name 'x' is not defined >>>

Introduction to Computing Using Python Three ways to import module attributes 'an example module' def f(): 'function f' print('Executing f()') def g(): 'function g' print('Executing g()') x = 0 # global var 'an example module' def f(): 'function f' print('Executing f()') def g(): 'function g' print('Executing g()') x = 0 # global var example.py namespace __main__ >>> 3. Import all module attributes >>> from example import * >>> >>> from example import * >>> >>> from example import * >>> f() Executing f() >>> g() Executing g() >>> x 0 >>> >>> from example import * >>> f() Executing f() >>> g() Executing g() >>> x 0 >>> f module example f f() 0 0 gx g() g x

Introduction to Computing Using Python A class is a namespace >>> list.pop >>> list.sort >>> >>> list.pop >>> list.sort >>> __add__ namespace list __add__() sort() count x count() pop pop() A class is really a namespace The name of this namespace is the name of the class The names defined in this namespace are the class attributes (e.g., class methods)... A class is really a namespace The name of this namespace is the name of the class The names defined in this namespace are the class attributes (e.g., class methods) The class attributes can be accessed using the standard namespace notation Function dir() can be used to list the class attributes >>> list.pop >>> list.sort >>> dir(list) ['__add__', '__class__',... 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> list.pop >>> list.sort >>> dir(list) ['__add__', '__class__',... 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

A class method is really a function defined in the class namespace; when Python executes it first translates it to and actually executes this last statement Introduction to Computing Using Python Class methods >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst [1, 2, 3, 7, 8, 9] >>> >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst [1, 2, 3, 7, 8, 9] >>> __add__ namespace list __add__() sort() count x count() pop pop()... >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst [1, 2, 3, 7, 8, 9] >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> list.sort(lst) >>> lst [1, 2, 3, 7, 8, 9] >>> >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst [1, 2, 3, 7, 8, 9] >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> list.sort(lst) >>> lst [1, 2, 3, 7, 8, 9] >>> >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst [1, 2, 3, 7, 8, 9] >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> list.sort(lst) >>> lst [1, 2, 3, 7, 8, 9] >>> lst.append(6) >>> lst [1, 2, 3, 7, 8, 9, 6] >>> >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst [1, 2, 3, 7, 8, 9] >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> list.sort(lst) >>> lst [1, 2, 3, 7, 8, 9] >>> lst.append(6) >>> lst [1, 2, 3, 7, 8, 9, 6] >>> >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst [1, 2, 3, 7, 8, 9] >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> list.sort(lst) >>> lst [1, 2, 3, 7, 8, 9] >>> lst.append(6) >>> lst [1, 2, 3, 7, 8, 9, 6] >>> list.append(lst, 5) >>> lst [1, 2, 3, 7, 8, 9, 6, 5] >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst [1, 2, 3, 7, 8, 9] >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> list.sort(lst) >>> lst [1, 2, 3, 7, 8, 9] >>> lst.append(6) >>> lst [1, 2, 3, 7, 8, 9, 6] >>> list.append(lst, 5) >>> lst [1, 2, 3, 7, 8, 9, 6, 5] lst.sort() list.sort(lst) lst.append(6) instance.method(arg1, arg2, …) list.append(lst, 6) class.method(instance, arg1, arg2, …) The function has an extra argument, which is the object invoking the method

Rewrite the below Python statement so that instead of making the usual method invocations you use the notation Introduction to Computing Using Python Exercise >>> s = 'hello' >>> s = 'ACM' >>> s.lower() 'acm' >>> s.find('C') 1 >>> s.replace('AC', 'IB') 'IBM' >>> s = 'hello' >>> s = 'ACM' >>> s.lower() 'acm' >>> s.find('C') 1 >>> s.replace('AC', 'IB') 'IBM' lst.sort() list.sort(lst) lst.append(6) instance.method(arg1, arg2, …) list.append(lst, 6) class.method(instance, arg1, arg2, …) >>> s = 'ACM' >>> str.lower(s) 'acm' >>> str.find(s, 'C') 1 >>> str.replace(s, 'AC', 'IB') 'IBM' >>> >>> s = 'ACM' >>> str.lower(s) 'acm' >>> str.find(s, 'C') 1 >>> str.replace(s, 'AC', 'IB') 'IBM' >>>