Functions. Learning Outcomes 10/1/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17

Similar documents
2.5 Methods. You may have heard this song from when you were a child:

CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions. User Defined Functions

MITOCW watch?v=flgjisf3l78

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

LOOPS. Repetition using the while statement

File Input/Output. Learning Outcomes 10/8/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01. Discussion Sections 02-08, 16, 17

MITOCW watch?v=kz7jjltq9r4

UNIT 6. Functions and Structured Programming

Lecture 26: Review. CS105: Great Insights in Computer Science Michael L. Littman, Fall : Introduction

Week - 01 Lecture - 03 Euclid's Algorithm for gcd. Let us continue with our running example of gcd to explore more issues involved with program.

Hello, World! EMT1111: Logic and Problem Solving Fall 2016 Dr. Mendoza

MITOCW watch?v=0jljzrnhwoi

Functions Structure and Parameters behind the scenes with diagrams!

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park

Arrays and Other Data Types

Short Answer Questions (40 points)

Writing and Understanding C++

Repetition, Looping CS101

Types, Expressions, and States

Writing and Understanding C++

6.001 Notes: Section 8.1

Introduction to: Computers & Programming Defining Identifiers: Objects with Names

C Programming for Engineers Functions

CMSC 201 Fall 2018 Python Coding Standards

The first program: Little Crab

6.001 Notes: Section 15.1

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers Ana Tanase

Decisions, Decisions. Testing, testing C H A P T E R 7

Introduction to: Computers & Programming Defining Identifiers: Objects with Names

Text Input and Conditionals

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG

Week - 01 Lecture - 04 Downloading and installing Python

Announcements. CompSci 101 Introduction to Computer Science. APT organization, Code organization. Organization matters

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

4.2 Function definitions the basics

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Lab 4 CSE 7, Spring 2018 This lab is an introduction to using logical and comparison operators in Matlab.

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Lecture 04 FUNCTIONS AND ARRAYS

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

CSCE 121 ENGR 112 List of Topics for Exam 1

In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

CMSC 201 Fall 2016 Homework 6 Functions

CircuitPython 101: Working with Lists, Iterators and Generators

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

Condition Controlled Loops. Introduction to Programming - Python

Intro. Speed V Growth

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

Racket Style Guide Fall 2017

CMSC201 Computer Science I for Majors

Python Debouncer Library for Buttons and Sensors

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Dr. Scheme evaluates expressions so we will start by using the interactions window and asking Dr. Scheme to evaluate some expressions.

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

CMSC201 Computer Science I for Majors

3 The L oop Control Structure

CSCE 110: Programming I

5. Control Statements

Extending Jython. with SIM, SPARQL and SQL

Most of the class will focus on if/else statements and the logical statements ("conditionals") that are used to build them. Then I'll go over a few

Lecture 7: Functions. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

Lists, loops and decisions

The following content is provided under a Creative Commons license. Your support

Scientific Computing: Lecture 3

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

Starting. Read: Chapter 1, Appendix B from textbook.

Chapters 1 & 2 Programming and Programs

The design recipe. Readings: HtDP, sections 1-5. (ordering of topics is different in lectures, different examples will be used)

Introduction to Modules. Chapter 3. Defining and Calling a Module. Introduction to Modules. 5 Benefits of Modules. Modules CSUS, Spring 2016

Lecture 4 8/24/18. Expressing Procedural Knowledge. Procedural Knowledge. What are we going to cover today? Computational Constructs

Intro. Scheme Basics. scm> 5 5. scm>

MITOCW watch?v=rvrkt-jxvko

cs1114 REVIEW of details test closed laptop period

Unit E Step-by-Step: Programming with Python

CS 115 Lecture 4. More Python; testing software. Neil Moore

Lecture 02 Making Decisions: Conditional Execution

Introduction to Programming

CSC236 Week 5. Larry Zhang

CS 231 Data Structures and Algorithms, Fall 2016

Functions. Using Bloodshed Dev-C++ Heejin Park. Hanyang University

MITOCW watch?v=hverxup4cfg

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

Unit 4: Client View of a Component Methods

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

CS 111X - Fall Test 1 - KEY KEY KEY KEY KEY KEY KEY

There are functions to handle strings, so we will see the notion of functions itself in little a detail later. (Refer Slide Time: 00:12)

Chapter 9: Dealing with Errors

Warmup : Name that tune!

Divisibility Rules and Their Explanations

Repetition, Looping. While Loop

Transcription:

Functions CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17 1 Adapted from slides by Sue Evans et al. 2 Learning Outcomes Understand why programmers divide programs up into sets of cooperating functions. Have the ability to define new functions in Python. Understand the details of function calls and parameter passing. Understand the distinction between functions, procedures and predicate functions. 3 1

What Are Functions? Functions define segments of code, similar to a subprogram Functions can be called at any time in a program Functions are generally useful when you need to repeatedly use a segment of code 4 What Are Functions? Functions in programming are analogous to functions in math such as f(x) = 2x We have actually used functions previously from the Python Modules such as math.sqrt(x) In this case sqrt is the name of a function defined in the math module 5 Why Use Functions? Two main purposes: Reuse: Can be called many times within a program Can be reused and called from other programs Validated once, used many times Modularity Embodies top-down design Decompose a large task into a sequential series of smaller tasks Decompose a task into a hierarchy of subtasks 6 2

Review of Top-Down Design Involves repeatedly decomposing a problem into smaller problems Eventually leads to a collection of small problems or tasks each of which can be easily coded The function construct in Python is used to write code for these small, simple problems. Functions A Python program is made up of one or more functions, one of which is usually main( ). Execution by convention begins with main( ) When program control encounters a function name, the function is called (invoked). Program control passes to the function. The function is executed. Control is passed back to the calling function. Sample Programmer-Defined Function import string def PrintMessage ( ): # A very simple function print A message for you:\n\n ) print Have a nice day!\n ) return 0 def main ( ): PrintMessage ( ) 3

Examining printmessage import string def PrintMessage (): # A very simple function print A message for you:\n\n print Have a nice day!\n return 0 function header function body function definition def main ( ): PrintMessage ( ) function call The Function Call Passes program control to the function Must match the function definition in number of arguments, and their purpose def PrintMessage () : def main ( ): same name no arguments PrintMessage ( ) The Function Definition Control is passed to the function by the function call. The statements within the function body will then be executed. def PrintMessage ( ): print A message for you:\n\n print Have a nice day!\n After the statements in the function have completed, control is passed back to the calling function, in this case main( ). (Note that the calling function does not have to be main( ).) 4

A Song-singing Program Let's write a program that "sings" Old MacDonald's Farm: # Filename: farm1.py # Written by: Sue Evans # Date: 7/31/09 # Section: All # Email: bogar@cs.umbc.edu # # This program "sings" Old MacDonald's Farm def : print "" print "And on that farm he had a cow, Ee-igh, Ee-igh, Oh!" print "With a moo, moo here and a moo, moo there." print "Here a moo, there a moo, everywhere a moo, moo." print "" 13 A Song-singing Program Let's see if it works: linuxserver1.cs.umbc.edu[117] python farm1.py And on that farm he had a cow, Ee-igh, Ee-igh, Oh! With a moo, moo here and a moo, moo there. Here a moo, there a moo, everywhere a moo, moo. linuxserver1.cs.umbc.edu[118] 14 A Song-singing Program Of course it works. There was nothing difficult about writing this code, except I got tired of typing "Ee-igh, Ee-igh, Oh!" So whenever you find yourself typing the same code over and over again, you should make a module out of that code by putting it in a function. 15 5

Defining a Function Functions are defined using the following form: def <function-name>(<parameters>): <block> def is a keyword that tells the system you are about to define a function. The <function-name> is a name of your choosing and must be different than any other functions you've defined. 16 Defining a Function All function names are followed with parentheses. Inside the parentheses are the names of the variable parameters, if there are any (to be discussed later). Using the same format as if statements discussed earlier, we then use the colon, : and then the tab-indented notation to specify the code block of the function. The code block is the code that will be executed when a function is called. 17 Defining a Function The first line of a function, i.e. def <function-name>(<parameters>): is known as the function header and the block of code beneath it is known as the function body. Below we've defined a function named chorus that prints the text, "Ee-igh, Ee-igh, Oh!" def chorus(): print Ee-igh, Ee-igh, Oh! 18 6

Calling a Function In order to call the function and execute its code, all we do is type the function name followed by the parentheses. We can call a function as many times as we want. Let's rewrite the song using our new function 19 Calling a Function # [Filename: farm2.py [rest of formal header not shown] # chorus() prints the chorus of Old MacDonald's farm # Inputs: none # Outputs: none def chorus(): print "Ee-igh, Ee-igh, Oh!" def : print "Old MacDonald had a farm,", chorus() print "And on that farm he had a cow,", chorus() print "With a moo, moo here and a moo, moo there." print "Here a moo, there a moo, everywhere a moo, moo." print "Old MacDonald had a farm,", chorus() 20 Calling a Function Does it work correctly? linuxserver1.cs.umbc.edu[120] python farm2.py And on that farm he had a cow, Ee-igh, Ee-igh, Oh! With a moo, moo here and a moo, moo there. Here a moo, there a moo, everywhere a moo, moo. linuxserver1.cs.umbc.edu[121] 21 7

Functions That Call Other Functions We can also define functions that call other functions. Since our song has a repeated line at the beginning and end of the verse, let's write a function called line(). Since the end of the line is "Ee-igh, Ee-igh, Oh!", we'll be calling the function chorus() to do that. Our program now looks like this : 22 Functions That Call Other Functions # [Filename: farm3.py [rest of formal header not shown] # chorus() prints the chorus of Old MacDonald's farm # Inputs: none # Outputs: none def chorus(): print "Ee-igh, Ee-igh, Oh!" # line() prints the repeated line of Old MacDonald's farm # Inputs: none # Outputs: none def line(): print "Old MacDonald had a farm,", chorus() # (continued next page) 23 # (continued) Functions That Call Other Functions def : line() print "And on that farm he had a cow,", chorus() print "With a moo, moo here and a moo, moo there." print "Here a moo, there a moo, everywhere a moo, moo." line() 24 8

Functions That Call Other Functions Be careful not to define functions with the same name, or you will overwrite the previous function definition without warning! >>> def duplicatename():... print "First Definition"... >>> duplicatename() First Definition >>> def duplicatename():... print "Second Definition"... >>> duplicatename() Second Definition 25 We're not really finished with Old MacDonald yet, because if we want to sing several verses, where each verse uses a different animal name and sound, we would either have to have a huge or write a separate function for every possible animal. Neither of the functions we wrote in the previous example had parameters. By using parameters, we can define just one function that can handle all of the animals and their sounds, one at a time : 26 # verse() prints an entire verse of Old MacDonald's farm # Inputs: animal - an animal's name # sound - the sound that animal makes # Outputs: none def verse(animal, sound): print line() print "And on that farm he had a %s," % (animal), chorus() print "With a %s, %s here" % (sound, sound), print "and a %s, %s there" % (sound, sound) print "Here a %s, there a %s," % (sound, sound), print "everywhere a %s, %s." % (sound, sound) line() 27 9

Notice in the parentheses following verse we included animal and sound separated by a comma--these are known as the function's parameters. animal and sound serve as variables the function can use - as we see in the line : print "And on that farm he had a %s," % (animal), 28 So, any variables specified between the parentheses in a function's definition are parameters for the function. The value of a function's parameters are assigned by evaluating the arguments when the function is called def : verse("cow", "moo") 29 In, when we called the function verse(), we gave the arguments "cow" and "moo" so the variable animal was assigned "cow" and sound was assigned "moo". The values of those variables were printed out in the song. linuxserver1.cs.umbc.edu[149] python farm4.py And on that farm he had a cow, Ee-igh, Ee-igh, Oh! With a moo, moo here and a moo, moo there Here a moo, there a moo, everywhere a moo, moo. linuxserver1.cs.umbc.edu[150] 30 10

Arguments are always passed to the function in the order they are entered. In our song program, the first argument passed to the function verse will always be assigned into the function's variable named animal and the second argument passed will always be assigned into the function's variable named sound. The names of the variables don't play into this process at all, only the positions in the parameter list matter. 31 To illustrate, let's make a mistake when we call the function from. def : verse( oink", pig") 32 Here s what it produced: linuxserver1.cs.umbc.edu[107] python farm7.py And on that farm he had a oink, Ee-igh, Ee-igh, Oh! With a pig, pig here and a pig, pig there Here a pig, there a pig, everywhere a pig, pig. linuxserver1.cs.umbc.edu[108] 33 11

Because the arguments are always evaluated before they are passed, you can also use variables as arguments. def : ananimal = "pig" asound = "oink" verse(ananimal, asound) 34 produces the following output: linuxserver1.cs.umbc.edu[153] python farm6.py And on that farm he had a pig, Ee-igh, Ee-igh, Oh! With a oink, oink here and a oink, oink there Here a oink, there a oink, everywhere a oink, oink. linuxserver1.cs.umbc.edu[154] 35 Since we've written these functions, we can easily sing as many verses as we want with very little additional code. In fact, that additional code will be in. Here's the final edit of the program: 36 12

# [Filename: farm5.py [rest of formal header not shown] # # This program "sings" many verses of Old MacDonald's Farm # making use of the chorus(), line() and verse() functions. # chorus() prints the chorus of Old MacDonald's farm # Inputs: none # Outputs: none def chorus(): print "Ee-igh, Ee-igh, Oh!" # line() prints the repeated line of Old MacDonald's farm # Inputs: none # Outputs: none def line(): print "Old MacDonald had a farm,", chorus() # (continued next page) 37 # (continued) # verse() prints an entire verse of Old MacDonald's farm # Inputs: animal - an animal's name # sound - the sound that animal makes # Outputs: none def verse(animal, sound): print line() print "And on that farm he had a", animal, "", chorus() print "With a %s, %s here" % (sound, sound), print "and a %s, %s there" % (sound, sound) print "Here a %s, there a %s," % (sound, sound), print "everywhere a %s, %s." % (sound, sound) line() # (continued next page) 38 # (continued) def : verse("cow", "moo") verse("pig", "oink") verse("hen", "cluck") verse("duck", "quack") verse("cat", "meow") 39 13

and the output looks like this : linuxserver1.cs.umbc.edu[109] python farm5.py And on that farm he had a cow Ee-igh, Ee-igh, Oh! With a moo, moo here and a moo, moo there Here a moo, there a moo, everywhere a moo, moo. And on that farm he had a pig Ee-igh, Ee-igh, Oh! With a oink, oink here and a oink, oink there Here a oink, there a oink, everywhere a oink, oink. And on that farm he had a hen Ee-igh, Ee-igh, Oh! With a cluck, cluck here and a cluck, cluck there Here a cluck, there a cluck, everywhere a cluck, cluck. 40 And on that farm he had a duck Ee-igh, Ee-igh, Oh! With a quack, quack here and a quack, quack there Here a quack, there a quack, everywhere a quack, quack. And on that farm he had a cat Ee-igh, Ee-igh, Oh! With a meow, meow here and a meow, meow there Here a meow, there a meow, everywhere a meow, meow. linuxserver1.cs.umbc.edu[110] 41 The code we produced is certainly preferable to the naive way to accomplish the same task : # Filename: farm1.py # Written by: Sue Evans # Date: 7/31/09 # Section: All # Email: bogar@cs.umbc.edu # # This program "sings" Old MacDonald's Farm def : print print "" print "And on that farm he had a cow, Ee-igh, Ee-igh, Oh!" print "With a moo, moo here and a moo, moo there." print "Here a moo, there a moo, everywhere a moo, moo." print "" print 42 14

print "" print "And on that farm he had a pig, Ee-igh, Ee-igh, Oh!" print "With a oink, oink here and a oink, oink there." print "Here a oink, there a oink, everywhere a oink, oink." print "" print print "" print "And on that farm he had a hen, Ee-igh, Ee-igh, Oh!" print "With a cluck, cluck here and a cluck, cluck there." print "Here a cluck, there a cluck, everywhere a cluck, cluck." print "" print print "" print "And on that farm he had a duck, Ee-igh, Ee-igh, Oh!" print "With a quack, quack here and a quack, quack there." print "Here a quack, there a quack, everywhere a quack, quack." print "" 43 print print "" print "And on that farm he had a cat, Ee-igh, Ee-igh, Oh!" print "With a meow, meow here and a meow, meow there." print "Here a meow, there a meow, everywhere a meow, meow." print "" 44 A great thing about using the version with functions is that we can add new animals to the song quickly and easily. Adding one more call to the function verse() produces another whole verse with the animal and sound passed. verse("sheep", "baa") 45 15

Kinds of Functions When refering to functions, it is sometimes useful to differentiate them into types that depend upon what they return. functions - return values predicate functions - return booleans procedures - return nothing, or None in python Let's see an example of a predicate function. Predicate functions typically use the word is as part of their name: 46 Kinds of Functions # isprime() takes a positive integer as an argument # and returns True if that integer is a prime number # and False if the number is not prime. # Input: a positive integer, num # Output: either True or False # Assumptions: num will be an integer > 1 def isprime(num): # try to evenly divide num by all # numbers between 2 and num - 1 for i in range(2, num): # if num is evenly divisible by this # number, then it isn't prime if num % i == 0: return False # if num wasn't divisible by any of # those numbers, then it's prime return True 47 We use it Kinds of Functions def : # print primes from 2 to 11, inclusive for i in range (2, 12): if isprime(i): print i, and here s the output: linuxserver1.cs.umbc.edu[118] python isprime.py 2 3 5 7 11 linuxserver1.cs.umbc.edu[119] 48 16

Kinds of Functions All of the functions we wrote for singing "Old MacDonald's Farm" are procedures. Here's one of those functions : def : # print primes from 2 to 11, inclusive for i in range (2, 12): if isprime(i): print i, Notice that the outputs say none. Outputs specify what is being returned and so it should say none. The fact that this function prints "Ee-igh, Ee-igh, Oh!" is the effect of the function, not the output. 49 Kinds of Functions If we wanted to make our function header comment more precise we could add an Effect: line; this is not a requirement. Here's the change : # chorus() prints the chorus of Old MacDonald's farm # Inputs: none # Outputs: none # Effect: prints "Ee-igh, Ee-igh, Oh!" def chorus(): print "Ee-igh, Ee-igh, Oh!" All of your homeworks and projects should contain a procedure named printgreeting(), which tells the user about the program they are about to run. 50 List Exercise In groups of 3 or 4, write a program that will print the even integers in a range that the user enters. Your program must have the following: a file-header comment function header comments for each function other than a procedure named printgreeting() a predicate function named iseven(value) don't forget to call 51 17

List Exercise Here s the output: Enter the starting number: 11 Enter the ending number: 21 The even numbers between 11 and 21 are: 12 14 16 18 29 52 18