Concepts when Python retrieves a variable’s value Namespaces – Namespaces store information about identifiers and the values to which they are bound –

Slides:



Advertisements
Similar presentations
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Advertisements

Methods Java 5.1 A quick overview of methods
Lilian Blot CORE ELEMENTS PART V: FUNCTIONS PARAMETERS & VARIABLES SCOPE Lecture 5 Autumn 2014 TPOP 1.
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
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Introduction to Computing Using Python Namespaces and Exceptions, revisited  Encapsulation in Functions  Global versus Local Namespaces  Exceptional.
Pemrograman Dasar - Data Types1 OPERATOR. Pemrograman Dasar - Data Types2 Arithmetic operator  + - * /  / operator denotes integer division if both.
Tcl and Otcl Tutorial Part I Internet Computing KUT Youn-Hee Han.
 2002 Prentice Hall. All rights reserved Control Structures 3 control structures –Sequential structure Built into Python –Selection structure The.
1 Fundamental Data types Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions l Assignment statement l Increment.
Structured programming
 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.
 2002 Prentice Hall. All rights reserved. 1 Intro: Java/Python Differences JavaPython Compiled: javac MyClass.java java MyClass Interpreted: python MyProgram.py.
BIL101, Introduction to Computers and Information Systems Chapter 12 A Portable Scientific Visualization Program: GnuPlot Prepared by Metin Demiralp Istanbul.
 2002 Prentice Hall. All rights reserved. 1 Chapter 2 – Introduction to Python Programming Outline 2.1 Introduction 2.2 First Program in Python: Printing.
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.
1 Data types, operations, and expressions Continued l Overview l Assignment statement l Increment and Decrement operators l Short hand operators l The.
Introduction to Computing Using Python Dictionary container class + modules  Container Class dict  Modules, revisited.
CSC 110 Numeric data types [Reading: chapter 3] CSC 110 D 1.
Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.
1 Chapter 9 Scope, Lifetime, and More on Functions.
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.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
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.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
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.
Lists and the ‘ for ’ loop. Lists Lists are an ordered collection of objects >>> data = [] >>> print data [] >>> data.append("Hello!") >>> print data.
1 Math Expressions and Operators. 2 Some C++ Operators Precedence OperatorDescription Higher ( )Function call +Positive - Negative *Multiplication / Division.
Chapter Function Basics CSC1310 Fall Function function (subroutine, procedure)a set of statements different inputs (parameters) outputs In.
Functions Chapter 4 Python for Informatics: Exploring Information
CSCI/CMPE 4341 Topic: Programming in Python Chapter 5: Functions Xiang Lian The University of Texas – Pan American Edinburg, TX
Python Functions.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Department of Electrical and Computer Engineering Introduction to C++: Primitive Data Types, Libraries and Operations By Hector M Lugo-Cordero August 27,
CSCE 121: Introduction to Program Design and Concepts, Honors J. Michael Moore Spring 2015 Set 14: Plotting Functions and Data 1.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
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.
Function Basics. Function In this chapter, we will move on to explore a set of additional statements that create functions of our own function (subroutine,
Data Types and Conversions, Input from the Keyboard CS303E: Elements of Computers and Programming.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(
Lecture 4 Python Basics Part 3.
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
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.
Functions Chapter 4 Python for Informatics: Exploring Information Slightly modified by Recep Kaya Göktaş on March 2015.
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.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
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 9: Value-Returning Functions
Chapter 6 - Functions modular programming general function format
G. Pullaiah College of Engineering and Technology
Introduction to Python
C Short Overview Lembit Jürimägi.
Chapter 3 – Control Structures
G. Pullaiah College of Engineering and Technology
Terminal-Based Programs
Presentation transcript:

Concepts when Python retrieves a variable’s value Namespaces – Namespaces store information about identifiers and the values to which they are bound – Three types Local, global, and built-in They are checked by Python in that order Scope of a variable – The region of the program where the variable is accessible

Namespaces Local namespace – Contains variables that were created in a block of code, e.g. each function has a unique local namespace Global namespace – Stores the names of functions, classes, variables defined within the file or module on outermost level – Each module contains an identifier __name__ It holds the name of the module (“ math ”) or “ __main__ ” (we’ll see how that can be used) Built-in namespace – Contains functions such as raw_input, int, and range – The built-in namespace is included when the interpreter starts (thus we automatically have access to these functions)

Namespaces built_in global local import math def f(a): x = 7 print y x = 9 z = 13 f(z) range, raw_input, int, float,.. __name__ = ‘__main__’, math, f, x = 9, z = 13,.. a = 13, x = 7 ?

def f(a): q = 7 z = 13 f(z) global namespace local namespace z aqaq 13 7 f

built_in global local import math def f(a): x = 7 x = 9 z = 13 f(z) print x range, raw_input, int, float,.. __name__ = ‘__main__’, math, f, x = 9, z = 13,.. a = 13, x = 7 local x global x Value of x..? 9.

local namespace def f(a): q = 7 z = 13 f(z) a = 13, q = 7

built_in global local import math def f(a): global x x = 7 x = 9 z = 13 f(z) print x range, raw_input, int, float,.. __name__ = ‘__main__’, math, f, x =.., z = 13,.. a = 13 global x Value of x..? 7!

Using identifiers outside their scope Scope of a variable – The region of the program where the variable is accessible def area(r): pi = 3.15 return pi*r*r* a = area(1.0) print pi a = area(1.0) def area(r): pi = 3.15 return pi*r*r*  

def area(r): pi = 3.15 return pi*r*r* a = area(1.0) print pi a = area(1.0) def area(r): pi = 3.15 return pi*r*r*  

Function dir() >>> >>> dir() ['__builtins__', '__doc__', '__name__'] >>> >>> print __name__ __main__ >>> >>> x = 3 >>> dir() ['__builtins__', '__doc__', '__name__', 'x'] >>> >>> dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError',.... 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'round',.. built-in function dir() lists the identifiers in the current namespace Since this is not a module (but rather an interactive session), the value of __name__ is __main__ dir(__builtins__) lists identifiers in the __builtins__ module new global variable

Function help() >>> help(range) Help on built-in function range: range(...) range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2,..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. The function help( ) gives you help in the interactive mode

Listing identifiers in an imported module Python 2.2b2 (#26, Nov , 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import math >>> dir() ['__builtins__', '__doc__', '__name__', 'math'] >>> >>> print math >>> >>> dir( math ) ['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh','e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10','modf', 'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] >>> >>> math.sqrt( 9.0 ) 3.0 identifier math now points to a module dir(math) lists all identifiers in the math module

Importing only parts of a module The from/import statement – For importing only a specific part of a module – Takes identifiers from a module and inserts them directly into the current program’s name space (avoids e.g. math. prefix) >>> from math import sqrt >>> >>> dir() ['__builtins__', '__doc__', '__name__', 'sqrt'] >>> >>> sqrt( 9.0 ) 3.0 >>> >>> from math import sin, cos, tan >>> >>> dir() ['__builtins__', '__doc__', '__name__', 'cos', 'sin', 'sqrt', 'tan'] Now directly a part of the current namespace

Directly importing all identifiers from a module >>> from math import * >>> >>> dir() ['__builtins__', '__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp','log', 'log10', 'modf', 'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] Danger! If you already have a log() function with a different purpose (perhaps you are a captain and wrote the function to access the log of your spaceship..), it will be shadowed! Either just import math and use math.log(), or..

Binding new names to modules and module functions from import as – imports a function but gives it a different name: from math import log as logarithm You can also give a new name to an entire module: – import math as mathtoolbox

The __name__ identifier Documentation string. Printed by help() if called on this function This code is only executed if the file is python’ed directly, not if it is imported. gcd_function.py

threonine:~...ExamplePrograms% python gcd_function.py Input first integer > 0: 39 Input second integer > 0: 63 The greatest common divisor of 39 and 63 is 3 threonine:~...ExamplePrograms% python Python (#1, Nov , 20:02:35) [GCC 3.3.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import gcd_function as gcd_module >>> >>> print gcd_module.gcd( 39, 63) 3 >>> Executing file directly: Importing file:

Default Arguments A function may sometimes be called repeatedly with the same values – When this is true default arguments can be set Must appear to the right of any other arguments in the function definition’s argument list: def myfunction( a, b = 2, c = 3 ): Given values are ‘filled in from the left’ (resolves ambiguity) myfunction(6, 3) # set a and b, use default for c myfunction(6) # set a, use default for b and c – A default value can also be overridden: myfunction(6, 3, 7) # overrides default c value

def boxVolume( length = 3, width = 2, height = 1 ): return length * width * height print "The default box volume is:", boxVolume() print "\nThe volume of a box with length 10," print "width 2 and height 1 is:", boxVolume( 10 ) print "\nThe volume of a box with length 10," print "width 5 and height 1 is:", boxVolume( 10, 5 ) print "\nThe volume of a box with length 10," print "width 5 and height 2 is:", boxVolume( 10, 5, 2 ) The default box volume is: 6 The volume of a box with length 10, width 2 and height 1 is: 20 The volume of a box with length 10, width 5 and height 1 is: 50 The volume of a box with length 10, width 5 and height 2 is: 100 All default values usedThe 10 will replace the 3 and the other default values will be used No default values used Here two values are sent replacing the two left-most default values

Keyword Arguments Keyword arguments – You can use argument names as keywords: – Allows arguments to be passed in any order as long as they are explicitly stated: def myfunction( a = 2, b = 3 ):.. myfunction ( b = 5, a = 9 ) – Will use default values for those arguments that were not given by keyword: myfunction ( b = 5 ) # use a=2

Personal data: George, 53, president (US) Personal data: Tony, 53, prime minister (GB) Personal data: Ronald, 92, president (US) name can be used as keyword as well, even though it doesn’t have a default value Some of the arguments have default values The arguments are given new values except age which uses the default. Values need not be entered in order. Sets first argument, uses the defaults for all the others

How not to use keyword arguments >>> >>> def test( name, age = 10, town = “Canberra” ):... pass... >>> test( age = 30, “Alice" ) SyntaxError: non-keyword arg after keyword arg >>> >>> test( age = 30 ) Traceback (most recent call last): File " ", line 1, in ? TypeError: test() takes at least 1 non-keyword argument (0 given) Keyword arguments must appear to the right of any other arguments in a function call. Otherwise ambiguity may arise. Is “Alice” the value for name or town ? No value given for name which doesn’t have a default value