Final thoughts on functions F E B 2 5 T H

Similar documents
3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

G52CPP C++ Programming Lecture 13

Introduction to Bioinformatics

Week 6: Introduction to Programming for GIS and Spatial Data Analysis GEO GEO A

CMPE-013/L. Introduction to C Programming. Unit testing

S206E Lecture 19, 5/24/2016, Python an overview

Lecture 16: Static Semantics Overview 1

PL Recitation 9/21/2010

Hello, Functions! We define a function using the def keyword:

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Ruby: Introduction, Basics

Overview. Elements of Programming Languages. Objects. Self-Reference

1 Decorators. 2 Descriptors. 3 Static Variables. 4 Anonymous Classes. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers July 13, / 19

FUNCTION PARAMETER AND ARGUMENT

Introduction to Python

LECTURE 2. Python Basics

Object Oriented Programming in Python 3

CSE 401 Midterm Exam Sample Solution 11/4/11

CSI33 Data Structures

COMP 2718: Shell Scripts: Part 1. By: Dr. Andrew Vardy

Overview. Elements of Programming Languages. Objects. Self-Reference

Python in 10 (50) minutes

Fundamentals of Programming Session 12

Constructors and Destructors. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Part I: Introduction to Functions

Subroutines. Subroutines. The Basics. aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc.

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Not Quite C Compiler version 1.0 b1

Compiler Errors. Flash CS4 Professional ActionScript 3.0 Language Reference. 1 of 18 9/6/2010 9:40 PM

About Variables in Python F E B 1 1 T H

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

JavaScript: Sort of a Big Deal,

Ruby: Introduction, Basics

Constructors for classes

Senthil Kumaran S

CS 105 Perl: Perl subroutines and Disciplined Perl

Introduction and Functions Summer 2018 Discussion 0: June 19, 2018

cs1114 REVIEW of details test closed laptop period

perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl

Introducing Wybe a language for everyone

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Connexion Documentation

Built-in functions. You ve used several functions already. >>> len("atggtca") 7 >>> abs(-6) 6 >>> float("3.1415") >>>

A Fast Review of C Essentials Part II

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Functions: Decomposition And Code Reuse

CS240: Programming in C

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

Accelerating Information Technology Innovation

Programming Languages Third Edition. Chapter 7 Basic Semantics

Chapter 13: Copy Control. Overview. Overview. Overview

COMPUTING SCIENCE 3Z: PROGRAMMING LANGUAGES 3

Dynamic Data Flow Analysis for Object Oriented Programs

egrapher Language Reference Manual

translationstring Documentation

The Eobj Perl environment

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

Introduction to Python

CS61A Notes Week 13: Interpreters

COMS 3101 Programming Languages: Perl. Lecture 5

Decaf Language Reference Manual

Lecture 3: C Programm

CS112 Spring 2012 Dr. Kinga Dobolyi. Exam 2. Do not open this exam until you are told. Read these instructions:

Software Engineering CSE 335, Spring OO design: Concurrency and Distribution

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes

Python Evaluation Rules

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl

Writing Functions. Reading: Dawson, Chapter 6. What is a function? Function declaration and parameter passing Return values Objects as parameters

Accelerating Information Technology Innovation

Forth Meets Smalltalk. A Presentation to SVFIG October 23, 2010 by Douglas B. Hoffman

learning objectives learn about variables, their types and their values learn about different number representations

CS 2340 Objects and Design - Scala

learning objectives learn about variables, their types and their values learn about different number representations

6.096 Introduction to C++

Ruby: Introduction, Basics

Key Differences Between Python and Java

CSC Web Programming. Introduction to JavaScript

Programming Languages


P Test Program Flow Conceptual Model Discussion Document

Functions parameters, scope CS GMU

Chapter 3 Structure of a C Program

CSCI 141 Computer Programming I. Filip Jagodzinski

Introduce C# as Object Oriented programming language. Explain, tokens,

CSE 413 Programming Languages & Implementation. Hal Perkins Winter 2019 Ruby Containers, Blocks, and Procs

CHAPTER 7 Using Other SAS Software Products

CS558 Programming Languages

String Computation Program

UNIT 3

G Programming Languages - Fall 2012

Variables. Data Types.

Wiki markup is a core feature for Topic pages, tightly integrating all the other parts of Trac into a flexible and powerful whole.

CSCE 120: Learning To Code

Transcription:

Final thoughts on functions F E B 2 5 T H

Ordering functions in your code Will the following code work? Here the function is defined after the main program that is calling it. print foo() def foo(): return hello Will this work? Here functions are defined before the main program. But, foo2() is called before it is defined by foo1. def foo1(): return foo2() def foo2(): return hello print foo1()

How does Python process code with functions? def foo1(): return foo2() def foo2(): return hello print foo1() 1. Pythons starts scanning the code from the beginning of the file. 2. It notes down names of functions as it encounters their definitions. Note that the functions are not executed at this time. 3. It reaches the first executable statement (print foo1()) and since foo1 is known to Python, control is transferred to foo1. 4. In foo1, Python encounters a call to foo2. Function foo2 is also known to Python and so control is transferred to foo2.

Moral of this example? Define all functions before the main program. And then don t worry about the order in which the functions themselves are defined.

Scope of a variable The scope of a variable refers to the where and when a variable is available for use. Things were simple when we did not have functions. If we only had a main program: the scope of a variable extends from the point where the variable is first defined till the end of the program. In Python the scope of a variable can be dynamic.

Example of dynamic scope x = raw_input() if x: y = "hello" print y If the input is a non-empty string, then the scope of variable y starts at Line 3. Otherwise, the scope of y is empty, i.e., y is undefined.

Scope of variables inside functions Parameters and variables defined inside a function are local to that function. def foo(): var1 = hello return var1 + var1 # main program print foo() if var1 == hellohello : print foo() var1 is a variable that is local to foo(). It comes into existence when the first line of foo() is executed and it dies when we exit the function. var1 is not defined and this usage will cause an error.

Function parameters are also local def foo(x): var1 = hello return var1 + x # main program print foo( bye ) if x == hellohello : print foo() The variable x is undefined here because the parameter x lives only for the duration of the function

Mental model: version 1 1. Python creates a dictionary of variable names when it starts evaluating the main program. It uses this dictionary to insert, look up, and update variable names. 2. When the function foo is executed, a new dictionary of variable names, specific to foo is created. 3. First the parameter x is inserted into this dictionary. Then variable var1 is inserted. 4. Whenever we access a variable inside foo, foo s dictionary is looked up. 5. When the execution of foo is over, foo s dictionary is destroyed.

Global variables The mental model 1.0 explains why variables defined inside a function cannot be used in the main program. What about variables defined in the main program? Can they be used inside a function? def foo(x): var1 = "hello" return var1 + x + y y = "good" print foo("bye") y is a global variable that is defined in the main program, but can be used in the function that is called after it is defined.

Mental model: version 1.1 Here is a more correct version of item (4) Whenever we access a variable inside foo, foo s dictionary is looked up. If a variable is not found in foo s dictionary, then Python looks up the dictionary of the main (calling) program. This allows a function access to global variables.

Local variables override global variables def foo(x): y = "hello" return x + y y = "good" print foo("bye") print y This is a different, local y. During the function, all mention of y refers to this local y. y is a global variable This mechanism also gives local variables precedence. In the above example, the variable y is found in foo s dictionary and that is the variable that is accessed in foo.

Explicit global variables def foo(x): global y y = "hello" return x + y We are now explicitly declaring that the y we want to access inside foo() is the global variable y y = "good" print foo("bye") Print y global is a Python keyword. If it were not for the global y statement, the variable y being mentioned inside foo would have been defined in foo s dictionary and would be local to foo.

WARNING!! I would discourage the use of global variables, both implicit and explicit. Communication between functions or between the main program and a function should be explicit via parameters/arguments and returned values.