Perkovic, Chapter 7 Functions revisited Python Namespaces

Slides:



Advertisements
Similar presentations
Arithmetic Calculations
Advertisements

Methods Java 5.1 A quick overview of methods
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.
Python Mini-Course University of Oklahoma Department of Psychology Day 1 – Lesson 4 Beginning Functions 4/5/09 Python Mini-Course: Day 1 - Lesson 4 1.
Chapter Modules CSC1310 Fall Modules Modules Modules are the highest level program organization unit, usually correspond to source files and.
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.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Modular Programming With Functions
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
Introduction to Computing Using Python Namespaces and Exceptions, revisited  Encapsulation in Functions  Global versus Local Namespaces  Exceptional.
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
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.
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.
Introduction to Computing Using Python Dictionary container class + modules  Container Class dict  Modules, revisited.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers.
Exceptions COMPSCI 105 S Principles of Computer Science.
CSC 107 – Programming For Science. Announcements  Lectures may not cover all material from book  Material that is most difficult or challenging is focus.
CSC 110 Numeric data types [Reading: chapter 3] CSC 110 D 1.
Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.
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.
1 TAC2000/ Protocol Engineering and Application Research Laboratory (PEARL) MATH Functions in C Language.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Functions Reading/writing files Catching exceptions
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.
Input, Output, and Processing
By James Braunsberg. What are Modules? Modules are files containing Python definitions and statements (ex. name.py) A module’s definitions can be imported.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
Functions Chapter 4 Python for Informatics: Exploring Information
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
MA/CS 375 Fall 2002 Lecture 3. Example 2 A is a matrix with 3 rows and 2 columns.
Introduction to Computing Using Python Namespaces – Local and Global  The Purpose of Functions  Global versus Local Namespaces  The Program Stack 
Introduction to Computing Using Python Namespaces – Local and Global  The Purpose of Functions  Global versus Local Namespaces  The Program Stack 
PHY 107 – Programming For Science. Announcements  Lectures may not cover all material from readings  Material that is most difficult or challenging.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
MA/CS 375 Fall 2003 Lecture 3. .* Multiplication We can use the.* operator to perform multiplication entry by entry of two matrices:
MA/CS 375 Fall 2002 Lecture 2. Motivation for Suffering All This Math and Stuff Try the Actor demo from
29 January 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 4 Python Basics Part 3.
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.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 6 - Functions modular programming general function format
G. Pullaiah College of Engineering and Technology
Chapter 8 Text Files We have, up to now, been storing data only in the variables and data structures of programs. However, such data is not available.
Python’s Modules by E. Esin GOKGOZ.
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
Namespaces – Local and Global
Rocky K. C. Chang 15 November 2018 (Based on Dierbach)
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Introduction to Value-Returning Functions: Generating Random Numbers
Terminal-Based Programs
Topics Introduction to File Input and Output
Namespaces – Local and Global
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
Python Modules.
Presentation transcript:

Perkovic, Chapter 7 Functions revisited Python Namespaces Introduction to Computing Using Python Perkovic, Chapter 7 Functions revisited Python Namespaces Python error-handling

Why write code as functions? Introduction to Computing Using Python Why write code as functions? Modularity Code reuse Encapsulation: A function hides its implementation details from a “client” (the user of the function)

Encapsulation through local variables Introduction to Computing Using Python Encapsulation makes modularity and code reuse possible def double(y): x=2 print('x = {}, y = {}'.format(x,y)) return x*y x and y are local variables x and y exist only during the execution of a function call to double

Namespaces and modules Introduction to Computing Using Python A namespace is a mapping from names to objects Several different kinds of namespaces: Global: associated with idle window Local: associated with a function Module: associated with a .py file that is imported into another namespace

Local namespaces Introduction to Computing Using Python When a function is called, a new namespace is created. The namespace only exists for as long a the function is executing Variables defined within the function (local variables) exist within the function’s namespace It is not possible to access a local variable from another namespace Local variable names shadow any names within the global namespace, so that the global names are not accessible

Local namespace example Introduction to Computing Using Python >>> a=0 >>>def multiply(a,b): return a * b >>> a >>> multiply(2,3) # temporarily creates a new namespace 6 >>> b Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> b NameError: name 'b' is not defined

Global namespace The idle window is associated with a global namespace Introduction to Computing Using Python The idle window is associated with a global namespace Variables, functions, etc. that are defined in the idle window are in the global namespace Unlike local namespaces, the global namespace exists for as long as an idle window is open (although the namespace is cleared when you hit F5) Names that are in the global namespace are accessible form a local namespace, unless the name is shadowed

Global namespace example Introduction to Computing Using Python >>> a = 2 >>> def multiplyByA(b): return a * b >>> multiplyByA(3) 6 >>> def changeA(value): a = value # this is still the global a >>> changeA(5) >>> a 2

Module namespace A module is Python code that is written in a .py file Introduction to Computing Using Python A module is Python code that is written in a .py file The names in a module must be imported in order to use them There are 3 different kinds of import statements: import <module> from <module> import <name> from <module> import *

Module namespace, cont. import <module> Introduction to Computing Using Python import <module> names in module are brought into the global namespace, but must be referred to as <module>.<name> >>> import math >>> math.sqrt(2) 1.4142135623730951 >>> sqrt(2) Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> math.min(1,2) AttributeError: 'module' object has no attribute ‘sqrt'

Module namespace, cont. from <module> import <name> Introduction to Computing Using Python from <module> import <name> A name in the specified module are brought into the global namespace, and can be referred to by its name >>> from math import sqrt >>> sqrt(2) 1.4142135623730951

Module namespace, cont. from <module> import * Introduction to Computing Using Python from <module> import * All name in the specified module are brought into the global namespace, and can be referred to by its name >>> from math import * >>> min(1,2,3) 1 BUT, any previously defined names can no longer be referred to

Module namespace, cont. >>> sqrt = 5 Introduction to Computing Using Python >>> sqrt = 5 >>> from math import * >>> min(1,2,3) 1 >>> sqrt <built-in function sqrt> This might not be what you want

Module and names Introduction to Computing Using Python Importing a module using import <module> allows you to keep more than one meaning of a name This helps with programming modularity (hence the name module) If a large prorgramming project is broken up among several programmers, each can write a module with no concern about the names that other programmers use in their modules

Local vs. global variables Introduction to Computing Using Python A local variable one that is used within a function >>> a = 1 >>> def f(a,b): a = a * b return a >>> f(2,2) 4 >>> a 1

Local vs. global variables Introduction to Computing Using Python >>> a = 1 >>> def f(c,d): a = c * d return a >>> f(2,2) 4 >>> a 1

Using a global variable in a function Introduction to Computing Using Python >>> a = 1 >>> def f(c,d): global a a = c * d return a >>> f(2,2) 4 >>> a

Subtle distinctions between local and global variables Introduction to Computing Using Python Subtle distinctions between local and global variables >>> a = 2 >>> def f(b): return b * a >>> f(3) 6 >>> a 2

Subtle distinctions between local and global variables Introduction to Computing Using Python Subtle distinctions between local and global variables >>> a = 2 >>> def f(b): a = a * b return a >>> f(3) Traceback (most recent call last): File "<pyshell#52>", line 1, in <module> f(3) File "<pyshell#51>", line 2, in f UnboundLocalError: local variable 'a' referenced before assignment

How Python evaluates names Introduction to Computing Using Python When the Python interpreter needs to evaluate a name, it searches for the name definition in this order: the enclosing function call namespace the global (module) namespace the namespace of module builtins

Exceptions, revisited Introduction to Computing Using Python When program execution gets into an erroneous state, an exception object is created This object has a type that is related to the type of error The object contains information about the error The default behavior is to print this information and interrupt the execution of the statement that “caused” the error

Exceptional control flow Introduction to Computing Using Python Exceptional control flow Normal control flow 1. def h(n): 2. print('Start h') 3. print(1/n) 4. print(n) 5. 6. def g(n): 7. print('Start g') 8. h(n-1) 9. print(n ) 10. 11. def f(n): 12. print('Start f') 13. g(n-1) 14. print(n) The default behavior is to interrupt the execution of each “active” statement and print the error information contained in the exception object. >>> f(2) Start f Start g Start h Traceback (most recent call last): File "<pyshell#79>", line 1, in <module> f(2) File "/Users/me/ch7/stack.py", line 13, in f g(n-1) File "/Users/me/ch7/stack.py", line 8, in g h(n-1) File "/Users/me/ch7/stack.py", line 3, in h print(1/n) ZeroDivisionError: division by zero >>> >>> f(2) Start f Start g Start h >>> f(2) >>> f(2) Start f >>> f(2) Start f Start g n = 2 print('Start f') g(n-1) print(n) f(2) n = 2 print('Start f') f(2) n = 2 print('Start f') g(n-1) f(2) n = 2 f(2) n = 1 print('Start g') h(n-1) g(1) n = 1 print('Start g') h(n-1) print(n) g(1) n = 1 print('Start g') g(1) n = 1 g(1) n = 0 h(0) n = 0 print('Start h') print(1/n) print(n) h(0) n = 0 print('Start h') print(1/n) h(0) n = 0 print('Start h') h(0)

Catching and handling exceptions Introduction to Computing Using Python It is possible to override the default behavior (print error information and “crash”) when an exception is raised, using try/except statements If an exception is raised while executing the try block, then the block of the associated except statement is executed try: strAge = input('Enter your age: ') intAge = int(strAge) print('You are {} years old.'.format(intAge)) except: print('Enter your age using digits 0-9!') strAge = input('Enter your age: ') intAge = int(strAge) print('You are {} years old.'.format(intAge)) Custom behavior: Default behavior: >>> ========== RESTART ========== >>> Enter your age: fifteen Enter your age using digits 0-9! >>> ======================== RESTART ======================== >>> Enter your age: fifteen Traceback (most recent call last): File "/Users/me/age1.py", line 2, in <module> intAge = int(strAge) ValueError: invalid literal for int() with base 10: 'fifteen'

Format of a try/except statement pair Introduction to Computing Using Python The format of a try/except pair of statements is: The exception handler handles any exception raised in the try block The except statement is said to catch the (raised) exception try: <indented code block> except: <exception handler block> <non-indented statement> It is possible to restrict the except statement to catch exceptions of a specific type only try: <indented code block> except <ExceptionType>: <exception handler block> <non-indented statement>

Format of a try/except statement pair Introduction to Computing Using Python def readAge(filename): 'converts first line of file filename to an integer and prints it' try: infile = open(filename) strAge = infile.readline() age = int(strAge) print('age is', age) except ValueError: print('Value cannot be converted to integer.') It is possible to restrict the except statement to catch exceptions of a specific type only >>> readAge('age.txt') Value cannot be converted to integer. >>> >>> readAge('age.txt') Value cannot be converted to integer. >>> readAge('age.text') Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> readAge('age.text') File "/Users/me/ch7.py", line 12, in readAge infile = open(filename) IOError: [Errno 2] No such file or directory: 'age.text' >>> 1 fifteen age.txt default exception handler prints this

Multiple exception handlers Introduction to Computing Using Python def readAge(filename): 'converts first line of file filename to an integer and prints it' try: infile = open(filename) strAge = infile.readline() age = int(strAge) print('age is',age) except IOError: # executed only if an IOError exception is raised print('Input/Output error.') except ValueError: # executed only if a ValueError exception is raised print('Value cannot be converted to integer.') except: # executed if an exception other than IOError or ValueError is raised print('Other error.') It is possible to restrict the except statement to catch exceptions of a specific type only

Controlling the exceptional control flow Introduction to Computing Using Python 1. def h(n): 2. print('Start h') 3. print(1/n) 4. print(n) 5. 6. def g(n): 7. print('Start g') 8. h(n-1) 9. print(n ) 10. 11. def f(n): 12. print('Start f') 13. g(n-1) 14. print(n) >>> try: f(2) except: print('!!') Start f Start g Start h !! >>> try: f(2) except: print('!!') Start f Start g Start h >>> try: f(2) except: print('!!') Start f Start g >>> try: f(2) except: print('!!') >>> try: f(2) except: print('!!') Start f n = 2 print('Start f') g(n-1) f(2) n = 2 print('Start f') g(n-1) print(n) f(2) n = 2 print('Start f') f(2) n = 2 f(2) n = 1 g(1) n = 1 print('Start g') h(n-1) print(n) g(1) n = 1 print('Start g') h(n-1) g(1) n = 1 print('Start g') g(1) n = 0 print('Start h') print(1/n) print(n) h(0) n = 0 print('Start h') print(1/n) h(0) n = 0 h(0) n = 0 print('Start h') h(0)

Modules A module is a file containing Python code. Introduction to Computing Using Python 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. When the module is executed (imported), then the module is (also) a namespace. Built-in function dir() returns the names defined in a namespace >>> 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’] >>> math.sqrt <built-in function sqrt> >>> math.pi 3.141592653589793 To access the imported module’s attributes, the name of the namespace must be specified

Importing a module Introduction to Computing Using Python When the Python interpreter executes an import statement, it: Looks for the file corresponding to the module to be imported. Runs the module’s code to create the objects defined in the module. Creates a namespace where the names of these objects will live. When the Python interpreter executes an import statement, it: Looks for the file corresponding to the module to be imported. 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. current working directory Standard Library folders >>> 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'] >>>

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

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

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

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