Functions CMSC 201. Motivation Using the tools we have so far, we can easily write code to find the largest number in a list, right?

Slides:



Advertisements
Similar presentations
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Advertisements

CS0004: Introduction to Programming Repetition – Do Loops.
Recursion CMSC 201. Recursion Vs. Iteration Recursion and iteration are both methods of solving problems. An iterative solution to a problem is anything.
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.
Scripting Languages Perl Chapter #4 Subroutines. Writing your own Functions Functions is a programming language serve tow purposes: –They allow you to.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Introduction to C Programming
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
Chapter 6: Functions.
Functions. Program complexity the more complicated our programs get, the more difficult they are to develop and debug. It is easier to write short algorithms.
Subroutines Just like C, PERL offers the ability to use subroutines for all the same reasons – Code that you will use over and over again – Breaking large.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Lists in Python.
Python November 28, Unit 9+. Local and Global Variables There are two main types of variables in Python: local and global –The explanation of local and.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
Functions CMSC 201. Motivation Using the tools we have so far, we can easily write code to find the largest number in a list, right?
Variables and Expressions CMSC 201 Chang (rev )
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Python Tricks CMSC 201. Overview Today we are learning some new tricks to make our lives easier! Slicing and other tricks Multiple return values Global.
Chapter 8 More On Functions. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. First cut, scope.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
David Stotts Computer Science Department UNC Chapel Hill.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Python Functions.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
For Loops CMSC 201. Overview Today we will learn about: For loops.
Passing Arguments, Local/Global Variables Writing Functions( ) (Part 2)
Variables and Expressions CMSC 201. Today we start Python! Two ways to use python: You can write a program, as a series of instructions in a file, and.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
Chapter 3: User-Defined Functions I
Scope, Aliasing, Tuples & Mutability Intro2CS – week 4a 1.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Functions with Arguments and Return Values, Oh My! CS303E: Elements of Computers and Programming.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
CS 1110 Introduction to Programming Spring 2017
Topics Introduction to Repetition Structures
Functions CIS 40 – Introduction to Programming in Python
Topics Introduction to Repetition Structures
User-Defined Functions
Value returning Functions
6 Chapter Functions.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
CS 1111 Introduction to Programming Fall 2018
Topics Introduction to Functions Defining and Calling a Void Function
Methods and Data Passing
Introduction to Value-Returning Functions: Generating Random Numbers
Methods and Data Passing
Python Basics with Jupyter Notebook
COMPUTER PROGRAMMING SKILLS
Functions So far we've been using functions from the builtin module, which is automatically loaded in most cases. Occasionally we've accessed functions.
CISC101 Reminders Assignment 3 due today.
Global Variables Created by assignment statement placed at beginning of program and outside all functions Can be accessed by any statement in the program.
Methods and Data Passing
Defining Functions.
Presentation transcript:

Functions CMSC 201

Motivation Using the tools we have so far, we can easily write code to find the largest number in a list, right?

Motivation Using the tools we have so far, we can easily write code to find the largest number in a list, right? myList = [1, 2, 3, 4] largest = myList[0] for item in myList: if item > largest: largest = item print(largest)

Motivation What if we want to do this multiple times in our program? We don’t want to rewrite the code multiple times. What variables do we need access to in order to find the maximum of a list? What piece of information will we have when we’re done?

Functions We can create a function to find the maximum whenever we want to! Think of a function as a machine that you stick some input into, and your results pop out. So for our example, our listMax function would have to have the list go in, and would spit the maximum back out. myList Functio n code maximum

Vocab The inputs for a function are called arguments. A function can have as many arguments as it needs to fulfill its purpose. For example, a function that counts the number of times some number x appears in a list would need the number x, as well as the list. The result of a function is called the return value. In the example above, the return value would be the number of times x appears.

You’ve Called Functions Before! print("Hello") The thing you want to print. Print doesn’t return anything! It has a side effect, but doesn’t give anything back.

You’ve Called Functions Before! width = int(input("Enter the box width: ")) “Please enter the box width: “ is the argument, the prompt to the user. The return value of the int function is stored in width.

You’ve Called Functions Before! someVar = range(0, 40) This function requires two arguments, the start and end of the range you want. The return value of this function is stored in someVar (in this case, a list of the numbers between 0 and 40)

Functions So in general, when we want to call a function, we use the following format: result = functionName(arg1, arg2)

Writing a Function That’s great, but where do functions come from?

Making a Function Say we have the following code to find the maximum of a list: myList = [1, 2, 3, 4] largest = myList[0] for item in myList: if item > largest: largest = item And we want to be able to use it over and over.

Making a Function def max(myList): largest = myList[0] for item in myList: if item > largest: largest = item return largest def is the keyword for defining a function in python Max is the name of the function myList is the list we are finding the max of. ‘return’ is how the function knows what to send back to the main program.

The Life Cycle of a Function someList = [1, 2, 3, 4] maxNum = max(someList) def max(myList): largest = myList[0] for item in myList: if item > largest: largest = item return largest someList gets renamed my list and this code is run Whatever was in max gets stored in maxNum

Calling Functions Multiple Times otherList = [8, 9, 10] someList = [1, 2, 3, 4] maxNum = max(someList) otherNum = max(otherList) def max(myList): largest = myList[0] for item in myList: if item > largest: largest = item return largest someList gets renamed myList and this code is run Whatever was in largest gets stored in maxNum def max(myList): largest = myList[0] for item in myList: if item > largest: largest = item return largest Next time, otherList gets copied A different largest gets copied into otherNum

Note In the last example, when someList gets put into the function, it gets renamed as whatever parameter that function expects. So someList becomes myList. Also, a function only knows about the parameters it’s given! Variables from the original program don’t carry over!

Scope someList = [1, 2, 3, 4] b = 6 maxNum = max(someList) def max(myList): largest = myList[0] for item in myList: if item > largest: largest = item b = 10 return largest Even though the original program has a variable named b, this function doesn’t know about it!

Scope A name is considered defined in a function if there is an assignment to that name anywhere within the body of the function. In Python, this assignment creates a binding of the name to a value. The parts of a program where this binding is directly accessible is the scope that binding.

Scope (cont'd) The same name can be used in different scopes and different name spaces. Python has 4 scopes local scope scope of enclosing functions global built-in Python will look for bindings in this order.

Scope (cont'd) In a function, names defined in the function have local scope. These are usually called local variables. In a function, parameters are also local. Names defined outside of any function have global scope. These are usually called global variables. Local and global variables can have the same name, which can lead to much confusion.

Scope (cont'd) To avoid confusion between local and global variables with the same name: Use different names (not always convenient). Don't use global variables (not allowed in CMSC201, anyway). Initialize your local variables at the beginning of each function to make it obvious that they are local.

Exercise Write a function called average that returns the average of a list. Then show how you would call this function.

Exercise Write a function called average that returns the average of a list. Then show how you would call this function. def average(myList): sum = 0 for item in myList: sum = sum + item return sum/len(myList) result = average(myList)

Multiple Parameters In order to make a function with multiple parameters, you can simply say: def someFunction(parameter1, parameter2): You would call someFunction as follows: someFunction(10, 20) Parameter1 would have the value of 10, and parameter2 would have the value of 20. The parameters go in order.

The Life Cycle of a Function a = 10 b = 15 result = sum(a, b) def sum(num1, num2): return num1 + num2 a and b are copied into num1 and num2 respectively. num1+num2 gets returned into result.

Exercise Write a function that takes two lists as arguments and finds the sum of both lists. For example: listA = [1, 2, 3] listB = [3, 4, 5] result = sumTwoLists (listA, listB) print(result) Prints: 18

Exercise Write a function that takes two lists as arguments and finds the sum of both lists. def sumTwoLists(list1, list2): sum = 0 for item in list1: sum = sum + item for item in list2: sum = sum + item return sum

Exercise Note: Functions can call each other! def sumTwoLists(list1, list2): return sum(list1) + sum(list2) def sum(list1): sum = 0 for item in list1: sum = sum + item return sum

Exercise Note: Functions can call each other! myList = [1, 2, 3] otherList = [4, 5, 6] result =sumTwoLists(myList, otherList) def sum(list1): sum = 0 for item in list1: sum = sum + item return sum def sumTwoLists(list1, list2): return sum(list1) + sum(list2)

Even More Arguments Three arguments work the exact same way: someFunction(arg1, arg2, arg3) def someFunction(arg1, arg2, arg3): #code goes here

Return Statements A function can have multiple return statements! Imagine a function that just takes two numbers and returns the larger. def max(number1, number2): if number1 > number2: return number1 else: return number2 Either return statement ends the program.

Return Statements def max(number1, number2): if number1 > number2: return number1 else: return number2 a = 5 b = 10 result = max(a, b) Only one of these values gets returned!

Return Statements A return statement immediately stops the function. This code doesn’t make sense! Line-3 will never be reached, because the return statement ends the function! def someFunction(arg1): line-1 line-2 return someVariable line-3

Exercise Write a function called factorial that finds the factorial of a single argument.

Exercise Write a function called factorial that finds the factorial of a single argument. def factorial(num): result = 1 for count in range(1, num+1): result = count * result return num

Notes The name of the variables in the functions have nothing to do with anything outside of the function. Feel free to name arguments whatever you like, as long as it makes sense. Never name a variable and a function the same thing. This will confuse python terribly.

The Main Function From now on, we will be putting our code in a special function known as main. Main is always called first whenever a program is run. def main(): # All of you code should be here def someOtherFunctions(): # More code main()

When To Create Functions We use functions to organize our code. From now on in this class, we will use functions whenever possible. You should break your code up into functions when: You have a clear, self contained process that can be isolated from the code around it. You have an operation that may need to be performed multiple times. It will simplify the readability of your code.