FUNCTIONS in Python.

Slides:



Advertisements
Similar presentations
User Defined Functions
Advertisements

Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
Python Programming: An Introduction to Computer Science
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
VBA Modules, Functions, Variables, and Constants
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
Chapter 6: User-Defined Functions I
CS1061 C Programming Lecture 2: A Few Simple Programs A. O’Riordan, 2004.
1 Modularity In “C”. 2 What is Modularity?  Modularity, is the heart of the high level, structured languages.  Means breaking down a big problem into.
CS 201 Functions Debzani Deb.
Chapter 6: User-Defined Functions I
Guide To UNIX Using Linux Third Edition
Functions and abstraction Michael Ernst UW CSE 190p Summer 2012.
Functions A function is a snippet of code that performs a specific task or tasks. You use a multitude of functions daily when you do such things as store.
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.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
Functions, Procedures, and Abstraction Dr. José M. Reyes Álamo.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
CPS120: Introduction to Computer Science Functions.
CSC 110 Defining functions [Reading: chapter 6] CSC 110 G 1.
NA2204.1jcmt CSE 1320 Intermediate Programming C Program Basics Structure of a program and a function type name (parameters) { /* declarations */ statement;
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 6 Defining Functions.
Chapter 4 - Visual Basic Schneider1 Chapter 4 General Procedures.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Vahé Karamian Python Programming CS-110 CHAPTER 6 Defining Functions.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
1 Computer Science of Graphics and Games MONT 105S, Spring 2009 Lecture 17 Parameters, Scope, Return values.
Procedural Programming Criteria: P2 Task: 1.2 Thomas Jazwinski.
FUNCTIONS IN C++. DEFINITION OF A FUNCTION A function is a group of statements that together perform a task. Every C++ program has at least one function,
1 Program Planning and Design Important stages before actual program is written.
Loops and Simple Functions CS303E: Elements of Computers and Programming.
Xiaojuan Cai Computational Thinking 1 Lecture 6 Defining Functions Xiaojuan Cai (蔡小娟) Fall, 2015.
Modularity using Functions Chapter 4. Modularity In programming blocks of code often can be "called up" and reused whenever necessary, for example code.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Functions  A Function is a self contained block of one or more statements or a sub program which is designed for a particular task is called functions.
1 ICS103 Programming in C Lecture 8: Functions I.
Introduction to Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
Loops and Simple Functions COSC Review: While Loops Typically used when the number of times the loop will execute is indefinite Typically used when.
6. FUNCTIONS Rocky K. C. Chang October 4, 2015 (Adapted from John Zelle’s slides)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
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.
CMSC201 Computer Science I for Majors Lecture 13 – Functions
Lesson 06: Functions Class Participation: Class Chat:
Chapter 9: Value-Returning Functions
Exam #1 You will have exactly 30 Mins to complete the exam.
User-Written Functions
Python Programming: An Introduction to Computer Science
Topic: Functions – Part 2
Organization of Programming Languages
Functions CIS 40 – Introduction to Programming in Python
CMSC201 Computer Science I for Majors Lecture 10 – Functions (cont)
User-Defined Functions
MACRO Processors CSCI/CMPE 3334 David Egle.
User Defined Functions
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
CMSC201 Computer Science I for Majors Lecture 14 – Functions (Continued) Prof. Katherine Gibson Based on concepts from:
Lesson 06: Functions Class Chat: Attendance: Participation
5. Functions Rocky K. C. Chang 30 October 2018
G. Pullaiah College of Engineering and Technology
Topics Introduction to Functions Defining and Calling a Function
15-110: Principles of Computing
答題分佈 Python Programming, 2/e.
Loops and Simple Functions
What is a Function? Takes one or more arguments, or perhaps none at all Performs an operation Returns one or more values, or perhaps none at all Similar.
Functions Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Presentation transcript:

FUNCTIONS in Python

What Are Functions? Functions are sub-programs which perform tasks which may need to be repeated Some functions are “bundled” in standard libraries which are part of any language’s core package. We’ve already used many built-in functions, such as input(), eval(), etc. Functions are similar to methods, but may not be connected with objects Programmers can write their own functions

Why Write Functions? Reusability Fewer errors introduced when code isn’t rewritten Reduces complexity of code Programs are easier to maintain Programs are easier to understand

Function Elements Before we can use functions we have to define them. So there are two main elements to functions: 1. Define the function. The function definition can appear at the beginning or end of the program file. 2. Invoke or call the function. This usually happens in the body of the main() function, but subfunctions can call other subfunctions too.

Function definitions A function definition has two major parts: the definition head and the definition body. The definition head in Python has three main parts: the keyword def, the identifier or name of the function, and the parameters in parentheses. def average(total, num): identifier Formal parameters or arguments Don’t forget the colon : to mark the start of a statement bloc keyword

Function body The colon at the end of the definition head marks the start of the body, the bloc of statements. There is no symbol to mark the end of the bloc, but remember that indentation in Python controls statement blocs. def average(total, num): x = total/num return x Function body The value that’s returned when the function is invoked

Workshop Using the small function defined in the last slide, write a command line program which asks the user for a test score total and the number of students taking the test. The program should print the test score average.

Happy Birthday Example: Function Flow # happy.py # Simple illustration of functions. def happy(): print "Happy Birthday to you!" def sing(person): happy() print "Happy birthday, dear", person + "." def main(): sing("Fred") print sing("Lucy") sing("Elmer") main()

Functions: Formal vs. Actual Paramaters (and Arguments) # moveto.py from graphics import * def moveTo(object, point): c = object.getCenter() dx = point.getX() - c.getX() dy = point.getY() - c.getY() object.move(dx,dy) def main(): win = GraphWin() circ = Circle(Point(100,100), 20) circ.draw(win) p = win.getMouse() moveTo(circ, p) win.close() center = circ.getCenter() print center.getX(), center.getY() main() Formal Parameters Function definition Actual parameters or arguments Call or invocation of function; Arguments must be in correct order according to function definition

Scope of variables Variables are “valid” only within the function in which they are declared/initialized. The scope of the variable is LOCAL. Only when a variable is passed as a parameter to a function can another function “see” or use the variable—and then only its value. Thus it is possible to have two variables named the same within one source code file, but they will be different variables if they’re in different functions—and they could be different data types as well.

Scope of variables, cont. def calc_tax(x): x = x * 0.08 return x def add_shipping(subtot): subtot = subtot * 1.04 return subtot def main(): units = input(“Please enter the # of units”) firstTotal = units * 5.00 total = add_shipping(firstTotal) total = total + calc_tax(total) print “Your total is: “, total main() x has scope only in calc_tax function subtot has local scope only Invocation/call firstTotal is sent as a parameter, and returns a value stored in total

Functions: Return values Some functions don’t have any parameters or any return values, such as functions that just display. See Happy Birthday ex. above. But… “return” keyword indicates what value(s) will be kicked back after a function has been invoked def square(x): return x * x The call: output = square(myNum) Formal parameter Return value

Return value used as argument: Example of calculating a hypotenuse num1 = 10 num2 = 14 Hypotenuse = math.sqrt(sum_of_squares(num1, num2)) def sum_of_squares(x,y) t = (x*x) + (y * y) return t

Triangle2.py example Triangle2.py Text of triangle2.py

Returning more than one value Functions can return more than one value def hi_low(x,y): if x >= y return x, y else: return y, x The call: hiNum, lowNum = hi_low(data1, data2)

Functions modifying parameters So far we’ve seen that functions can accept values (actual parameters), process data, and return a value to the calling function. But the variables that were handed to the invoked function weren’t changed. The called function just worked on the VALUES of those actual parameters, and then returned a new value, which is usually stored in a variable by the calling function. This is called passing parameters by value

Passing parameters by value, example def add_shipping(subtot): subtot = subtot * 1.04 return subtot def main(): units = input(“Please enter the # of units”) firstTotal = units * 5.00 total = add_shipping(firstTotal) # total = total + calc_tax(total) print “Your total is: “, total main() Value of firstTotal is handed to add_shipping() function; firstTotal variable is not changed by add_shipping() The value returned by add_shipping() is stored in a new variable, total, in main()

Example of flawed function call # addinterest1.py # Program illustrates failed attempt to change value of a parameter def addInterest(balance, rate): newBalance = balance * (1+rate) balance = newBalance def test(): amount = 1000 rate = 0.05 addInterest(amount, rate) print amount test()

Flawed function call corrected # addinterest2.py # Illustrates use of return to change value in calling program. def addInterest(balance, rate): newBalance = balance * (1+rate) return newBalance def test(): amount = 1000 rate = 0.05 amount = addInterest(amount, rate) print amount test()

Modifying parameters, cont. Some programming languages, like C++, allow passing parameters by reference. Essentially this means that special syntax is used when defining and calling functions so that the function parameters refer to the memory location of the original variable, not just the value stored there. PYTHON DOES NOT SUPPORT PASSING PARAMETERS BY REFERENCE

Schematic of passing by value Memory location Main() 1011001 firstTotal add_shipping() Value becomes subtot here 25.90 Return value sent back to main() total

Schematic of passing by reference Memory location Main() 1011001 firstTotal add_shipping() Memory location passed to subfunction 25.90 Using memory location, actual value of original variable is changed

Passing lists in Python Python does NOT support passing by reference, BUT… Python DOES support passing lists, the values of which can be changed by subfunctions.

Example of Python’s mutable parameters # addinterest3.py # Illustrates modification of a mutable parameter (a list). def addInterest(balances, rate): for i in range(len(balances)): balances[i] = balances[i] * (1+rate) def test(): amounts = [1000, 2200, 800, 360] rate = 0.05 addInterest(amounts, 0.05) print amounts test()

Passing lists, cont. Because a list is actually a Python object with values associated with it, when a list is passed as a parameter to a subfunction the memory location of that list object is actually passed –not all the values of the list. When just a variable is passed, only the value is passed, not the memory location of that variable. Ergo, when the memory location of a list object is passed, a subfunction can change the values associated with that list object.

Modularize! Functions are useful in any program because they allow us to break down a complicated algorithm into executable subunits. Hence the functionalities of a program are easier to understand. This is called modularization. If a module (function) is going to be used more than once in a program, it’s particular useful—it’s reusable. E.g., if interest rates had to be recalculated yearly, one subfunction could be called repeatedly.