Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(

Slides:



Advertisements
Similar presentations
Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1.
Advertisements

Kernighan/Ritchie: Kelley/Pohl:
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Structured programming
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Functions in Python. The indentation matters… First line with less indentation is considered to be outside of the function definition. Defining Functions.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
CS61A Lecture 2 Functions and Applicative Model of Computation Tom Magrino and Jon Kotker UC Berkeley EECS June 19, 2012.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers.
Python Programming: An Introduction to Computer Science
Exceptions COMPSCI 105 S Principles of Computer Science.
Announcements Class / Recitation slides available on the syllabus page Check morning of for latest version We will start grading clickers next lecture.
Announcements Project 2 Available Tomorrow (we will send mail) Will be due 11:59PM October 9 th (Sunday) Week 6 ( I will be traveling this week) Review.
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
COMPSCI 101 Principles of Programming Lecture 28 – Docstrings & Doctests.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Functions and subroutines – Computer and Programming.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
 Expression Tree and Objects 1. Elements of Python  Literals, Strings, Tuples, Lists, …  The order of file reading  The order of execution 2.
Announcements Additional office hours tomorrow: 3-6pm in HAAS 142 Midterm Bring a #2 pencil (test given via scantron sheet) Photo ID No Labs or Recitation.
Announcements Project1 Due Wednesday September 21 st 4:30pm We will post instructions on how to turnin from home Note: you can always turn in from the.
CPS120: Introduction to Computer Science Functions.
Topics: IF If statements Else clauses. IF Statement For the conditional expression, evaluating to True or False, the simple IF statement is if : x = 7.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Topics: Function Intitution Algorithm Example Function Definition (and Indentation) Function Call Naming and Binding Local Variables Function Arguments.
Python Functions.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Announcements Survey link (can be found on piazza): OCJ6
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Xiaojuan Cai Computational Thinking 1 Lecture 6 Defining Functions Xiaojuan Cai (蔡小娟) Fall, 2015.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
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 in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
6. FUNCTIONS Rocky K. C. Chang October 4, 2015 (Adapted from John Zelle’s slides)
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
1 CS Review, iClicker -Questions Week 15. Announcements 2.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Announcements Reading Read Chapter 4 (functions).
Python Boot Camp Booleans While loops If statements Else clauses
Announcements Reading Project1 Codelab: Read Chapter 4 (functions)
Functions CIS 40 – Introduction to Programming in Python
CMSC201 Computer Science I for Majors Lecture 10 – Functions (cont)
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Topics Introduction to File Input and Output
CMSC201 Computer Science I for Majors Lecture 14 – Functions (Continued) Prof. Katherine Gibson Based on concepts from:
5. Functions Rocky K. C. Chang 30 October 2018
CISC181 Introduction to Computer Science Dr
G. Pullaiah College of Engineering and Technology
CISC101 Reminders All assignments are now posted.
15-110: Principles of Computing
答題分佈 Python Programming, 2/e.
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
Topics Introduction to File Input and Output
def-ining a function A function as an execution control structure
Presentation transcript:

Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction( ) The number of arguments is fixed; could be zero The function returns a value; could be None

Function Output The return statement specifies what value the function returns to the call site: return Return Statement Passing a value out of a function (output) Last statement executed Multiple conditional exit possible

Function Call as Substitution When a function is called The argument values are bound (assigned) to the parameter names The program of the function is executed as if those program statements were substituted for the call Upon execution of the return statement, the return value is substituted for the function call If no return statement is executed, and the program of the function body ends, the function returns None, indicating that no value is returned to the calling place.

Example x = 12 y = 4 def mySum(a,b): u = a+b x = 1 return u print(x,y) print(mySum(x,y)) print(x,y) Unless explicitly declared global, x is a local variable

More on Returns Returns are the last statement executed by a function The function is considered to be “done” at this point There may be other statements “after” the return, but these are not executed (but see conditionals later-on def sumOfTwo(a,b): return a+b print(a+b) print(sumOfTwo(4,5))

Stringing together functions We can build up complex expressions from functions def sumOfTwo(a,b): return a+b print(sumOfTwo(sumOfTwo(4,5), sumOfTwo(1,2))) OR a = sumOfTwo(4,5) b = sumOfTwo(1,2) c = sumOfTwo(a,b) print(c)

A “Sample” Program def task1(a,b): … y = …. return y def task2(a,b,c): …. z = … return z def main(): input1, input2 = eval(input(…)) output1 = task1(input1, input2) output2 = task2(input1, input2, output1) print(output2)

Local Variables Function parameter names act as local variables: They are available as variables for the execution of the function body They get their initial value from the values at the call site (value binding) When the function ends, they are no longer available You can define additional variables in the function body They will be local variables by default When the function ends, they no longer exist

Local Variables a = 3 y = 10 def myFun(a): print (a) y = 1 myFun(4) print(a) print(y)

Question: does this program print 3 or 4? x = 3 def myFun(): print (x) x = 4 myFun() (a)3 (b)4

Are these programs equivalent? #1 a = 3 def myFun(a): print (a) myFun(4) #2 a = 3 print (a) (a) Yes (b)No

Variables and Functions Variables defined outside of the function are global variables Global variables can be changed inside a function body Using global variables inside functions is dangerous: Multiple calls to a function may yield different results if the program “rebinds” such variables At minimum, declare global variables as global in the function body and document their use.

Variables and Functions x = 3 def myFun(): print (x) x = 4 myFun() x =5 myFun()

You must be careful! x = 3 def myFun(): print (x) x = 1 x = 4 myFun() x =5 myFun() ERROR!

Global Variables How can we get the example code we saw earlier to work? Python is not sure if we want x to be a local variable or if it should refer to the x we defined outside of the function We can inform python if we want x to refer to the variable outside of the function New keyword global

This works! x = 3 def myFun(): global x print (x) x =1 x = 4 myFun()

Global or Local? If the global keyword is used, the variable is global If the first use of the variable is a ‘read’ (reference), the variable is global NOTE: We cannot assign to such a variable later Function arguments are always local If the first use of the variable is a write (assignment), the variable is local Unless the variable is defined global

Clicker Question: Is x global or local? x = 3 def myFun(): y = 4 z = x + y myFun() A: global B: local

Let’s Review Functions take input and produce output Output is provided by the “return” statement Otherwise the function does not provide output At the call site of the function the arguments get bound The arguments can rebind variables that have already been defined for the duration of the call You can use global variables, defined outside the function, but you must be careful!

Advice Unless absolutely necessary avoid naming parameters and local variables the same as global variables

Argument Typing Functions typically assume something important about the arguments Will this work no matter what we provide as arguments? def sumOfTwo(a,b): return a+b

Function Arguments Consider the following three cases: One of these cases will throw an error. This behavior is defined by the code inside the function res = sumOfTwo(1,2) res = sumOfTwo(“Hello “, “World”) res = sumOfTwo(“Hello”, 1)

Function Arguments There are two ways to handle this difficulty 1. Tell everyone what the function expects 2. Include checks inside the function to ensure the arguments are what is expected A combination of both techniques should be used

Function Documentation This solution uses comments and if-statements. We will revisit this in later slides # This function expects two integers # and returns -1 otherwise def sumOfTwo(a,b): if type(a) == int and type(b) == int : return a+b return -1

Functions that Modify Parameters Suppose you are writing a program that manages bank accounts. One function we would need to do is to accumulate interest on the account. Let’s look at a first- cut at the function. def addInterest(balance, rate): newBalance = balance * (1 + rate) balance = newBalance

Functions that Modify Parameters The intent is to set the balance of the account to a new value that includes the interest amount. Let’s write a main program to test this: def test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print(amount)

Functions that Modify Parameters We hope that that the 5% will be added to the amount, returning >>> test() 1000 What went wrong? Nothing!

Functions that Modify Parameters The first two lines of the test function create two local variables called amount and rate which are given the initial values of 1000 and 0.05, respectively. def addInterest(balance, rate): newBal = balance*(1+rate) balance = newBal def test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print(amount) test()

Functions that Modify Parameters The first two lines of the test function create two local variables called amount and rate which are given the initial values of 1000 and 0.05, respectively. def addInterest(balance, rate): newBal = balance*(1+rate) balance = newBal def test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print(amount) test()

Functions that Modify Parameters def addInterest(balance, rate): newBalance = balance * (1 + rate) return newBalance def test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print(amount) test()

Functions that Modify Parameters def addInterest(balance, rate): newBalance = balance * (1 + rate) return newBalance def test(): amount = 1000 rate = 0.05 amount = addInterest(amount, rate) print(amount) test()

Functions that Modify Parameters Why is the following solution inferior? amount = 1000 rate = 0.05 def addInterest(): global amount global rate amount = amount * (1 + rate) addInterest() print(amount)

Libraries What is the difference between: 1. import library 2. from library import * Both provide you with a mechanism to utilize additional functionality in your program Version 1 requires referencing library functions using the object notation:. ( ) import math math.sqrt(x) Version 2 obligates you to use the function name without library reference: from math import * sqrt(x) If you mix the two Python throws an error

Libraries >>> from math import * >>> math.sqrt(4) Traceback (most recent call last): File " ", line 1, in math.sqrt(4) NameError: name 'math' is not defined >>> import graphics >>> win = GraphWin() Traceback (most recent call last): File " ", line 1, in win = GraphWin() NameError: name 'GraphWin' is not defined