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
Summer Computing Workshop. Introduction to Variables Variables are used in every aspect of programming. They are used to store data the programmer needs.
Advertisements

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?
Introduction to Programming G51PRG University of Nottingham Revision 3 Essam Eliwa.
Lists CMSC 201. Overview Today we will learn about: For loops.
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.
Computer Science 1620 Loops.
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.
Genome Sciences 373 Genome Informatics Quiz Section 5 April 28, 2015.
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.
COMP 171: Functions, for loops and range John Barr Section 03 Slides by Toby Dragon.
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.
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.
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.
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.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
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?
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)
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
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.
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.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
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.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
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.
Suppose we want to print out the word MISSISSIPPI in big letters.
CS 1110 Introduction to Programming Spring 2017
Topics Introduction to Repetition Structures
Suppose we want to print out the word MISSISSIPPI in big letters.
Module 4 Functions – function definition and function prototype.
Functions CIS 40 – Introduction to Programming in Python
Topics Introduction to Repetition Structures
User-Defined Functions
While Loops (Iteration 2)
Value returning Functions
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Coding Concepts (Basics)
CS 1111 Introduction to Programming Fall 2018
Topics Introduction to Functions Defining and Calling a Void Function
Methods and Data Passing
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.
Methods and Data Passing
Unit Testing.
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] max = myList[0] for item in myList: if item > max: max = item print(max)

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(“Please 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: resultValue = functionName(argument1, argument2)

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] max = myList[0] for item in myList: if item > max: max = item And we want to be able to use it over and over.

Making a Function def max(myList): max = myList[0] for item in myList: if item > max: max = item return max 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): max = myList[0] for item in myList: if item > max: max = item return max 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): maxNum = myList[0] for item in myList: if item > maxNum : maxNum = item return maxNum someList gets renamed myList and this code is run Whatever was in max gets stored in maxNum def max(myList): maxNum = myList[0] for item in myList: if item > maxNum : maxNum = item return maxNum Next time, otherList gets copied A different max gets copied into otherNum

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

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

Scope This concept is called scope. The variables given to a function as arguments and the variables defined inside the function constitute the scope of the function.

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)

Functions With 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 always 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.