Topics: Function Intitution Algorithm Example Function Definition (and Indentation) Function Call Naming and Binding Local Variables Function Arguments.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Intro Programming By Trevor Decker Team 1743 By Trevor Decker Team 1743.
CS 201 Functions Debzani Deb.
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.
CS 201 Functions Debzani Deb.
Programming – Touch Sensors Intro to Robotics. The Limit Switch When designing robotic arms there is always the chance the arm will move too far up or.
Functions in Python. The indentation matters… First line with less indentation is considered to be outside of the function definition. Defining Functions.
CS61A Lecture 2 Functions and Applicative Model of Computation Tom Magrino and Jon Kotker UC Berkeley EECS June 19, 2012.
PRINCIPLES OF PROGRAMMING Revision. A Computer  A useful tool for solving a great variety of problems.  To make a computer do anything (i.e. solve.
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.
Hello World 2 What does all that mean?.
Chapter 6 Functions 1. Opening Problem 2 Find the sum of integers from 1 to 10, from 20 to 37, and from 35 to 49, respectively.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 3 Simple.
By the end of this session you should be able to...
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
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.
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
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.
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.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
Announcements Survey link (can be found on piazza): OCJ6
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
1 Functions, Part 1 of 2 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function Header Comments.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Functions, Part 1 of 3 Topics  Using Predefined Functions  Programmer-Defined Functions  Using Input Parameters  Function Header Comments Reading 
COSC 1223 Computer Science Concepts I Joe Bryan. What is a function? Like a mini-program that performs a specific task Two types: Built-in functions Functions.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
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).
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Announcements Reading Project1 Codelab: Read Chapter 4 (functions)
User-Written Functions
Topic: Functions – Part 2
Think What will be the output?
Functions.
Repeating code We could repeat code we need more than once: i = 1 print (i) i += 1 print (i) #… stop when i == 9 But each line means an extra line we might.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park
Writing Functions( ) (Part 5)
Chapter 3 Simple Functions
Learning to Program in Python
Topics Introduction to File Input and Output
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
Functions, Part 1 of 3 Topics Using Predefined Functions
CS 1111 Introduction to Programming Fall 2018
Coding Concepts (Basics)
What does this do? def revList(L): if len(L) < = 1: return L x = L[0] LR = revList(L[1:]) return LR + x.
Topics Introduction to Functions Defining and Calling a Void Function
CISC101 Reminders All assignments are now posted.
Functions, Part 1 of 3 Topics Using Predefined Functions
Loops and Simple Functions
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
Topics Introduction to File Input and Output
Functions, Part 1 of 3 Topics Using Predefined Functions
2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park
Functions Taken from notes by Dr. Neil Moore & Dr. Debby Keen
def-ining a function A function as an execution control structure
Parameters and Arguments
Presentation transcript:

Topics: Function Intitution Algorithm Example Function Definition (and Indentation) Function Call Naming and Binding Local Variables Function Arguments Return

Functions input function output Arguments Return

Control Flow The term control flow is typically used to describe the order of execution in code This can be represented as a flow chart The End you will see in the flowcharts is not an actual programming construct. It merely represents where the chart ends. In simple programs code flows from the first line to the last line, one line at a time

a = 15 b = -7 print(a) print(b) print(a + b)

Intuition behind functions We want a mechanisms to allow for code reuse Consider if we have a program A and we want to write a new program that does what A does only twice a = 15 b = -7 print(a+b)

Program A’ a = 15 b = -7 print(a+b) a = 15 b = -7 print(a+b)

We can use a function! def A(): a = 15 b = -7 print(a+b) A() Abstractly a function provides a name to a piece of code

Algorithm Example: Read a book 1. Remove book from bag 2. Place book on desk 3. Open book to first page 4. Until end of book, Read() Let us now look at step 4 as a function call

Functions Read(): 1. Place eyes on top left corner of page 2. For each word on page 3. ReadWord() 4. If end of page is reached, change current page to next page

Defining A Function Function definitions start with def This is followed by the function name, and any arguments the function should have The : identifies the start of a block of code The body of the function is anything indented beneath this line def myFunction(a,b): print(a) print(b)

Arguments Functions have an important feature They can receive and return values Values are ‘passed to’ a function inside of ( ) when called and returned using a special instruction def myFunction( input_values ): return output_value

Functions Functions come up in two ways in programs Function Definition Where the function is created Starts with def in python Function Call Where the function is used result = myFunction(argument1,argument2)

Function Return If a function needs to return a value back to the place in the code where it is called it uses a return statement def myFunction(a,b): print(a) print(b) return a+b

Clicker Question: Are these programs equivalent? A: Yes B:No def myFun(a): print(a) return a print(myFun(4)) def myFun(a): print(a) print (myFun(4))

Function Call Once the function is defined it can be called as many times as one likes If the function has a return it can be stored into a variable at the call myFunction(6,7) myFunction(4,10) a = myFunction(6,7)

Example Revisited (but slightly modified) def myFun(a): print(a) return a+1 myFun(myFun(4))

Example Revisited (but slightly modified…again) def myFun(a): print(a) return a+1 b =myFun(4) myFun(b)

Question: Are these programs equivalent? a = 3 def myFun(a): print(a) a = 3 def myFun(a): print(a) 21 A: yes B: no

Clicker Question: Are these programs equivalent? A:Yes B:No a = 3 def myFun(b): print(b) print(a) myFun(3) a = 3 def myFun(b): print(b) myFun(3)

Indentation Indentation is very important in python In functions it defines where the function ends Python will give errors if the indentation is incorrect

Are these programs equivalent? A: Yes B:No a = 3 def myFun(a): print (a) myFun(4) a = 3 print (a)

Naming and Binding Arguments are bound at the “call site” Call site: a point in the program where the function is called The binding is active up until the return of the function

Naming and Binding a = 3 def myFun(a): print (a) myFun(4) print(a)

Local Variables We saw that arguments can be rebound for the duration of the call What about variables that we define in the function body?

Local Variables Abstractly there are two types of local variables 1) those which introduce a new variable 2) those which redefine an existing variable which was initially defined outside the function definition Local variables, just like arguments, have a lifetime associated with the function call

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

Clicker Question: Does this program print 3 or 4? A: 3 B:4 x = 3 def myFun(): print (x) x = 4 myFun()

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

Variables and Functions Variables used in functions but defined outside of the function can be changed Multiple calls to a function may yield different results if the program “rebinds” such variables

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

Lets 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 variables defined outside the function but you must be careful!

Function Arguments 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

What all can I do within the body of a function? Define local variables Call other functions Define new functions

Function calls as conditions? We have seen a lot of conditionals like: if x == 3: or if y: or if (x<3) and (y%3 ==0): But what about something like this? if myFun(x): This is equivalent to writing: z = myFun(x): if z: So it is just fine

Returns If a function does not specify a value to return it returns a special python value: “None” Just because a function has a return statement in it, does NOT mean it will return a value in every case >>> def example(x): if x < 10: print(x) else: return(30) >>> z = example(10) >>> print(z) 30 >>> z = example(9) 9 >>> print(z) None