6. FUNCTIONS Rocky K. C. Chang October 4, 2015 (Adapted from John Zelle’s slides)

Slides:



Advertisements
Similar presentations
Modular Programming With Functions
Advertisements

Python Programming: An Introduction to Computer Science
Adapted from John Zelle’s Book Slides
FUNCTIONS in Python.
CS 201 Functions Debzani Deb.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Introduction to Methods
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
CS 127 Writing Simple Programs.  Stages involved  Analyze the problem  Understand as much as possible what is trying to be solved  Determine Specifications.
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.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Chapter 06 (Part I) Functions and an Introduction to Recursion.
1 Functions Lecfture Abstraction abstraction is the process of ignoring minutiae and focusing on the big picture in modern life, we are constantly.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
Functions, Procedures, and Abstraction Dr. José M. Reyes Álamo.
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.
Introduction to Method. Example Java Method ( 1 ) The 2 types (kinds) of methods in Java Class methods Instance methods Methods can do more work than.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
CSC 110 Defining functions [Reading: chapter 6] CSC 110 G 1.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 6 Defining Functions.
Chapter 4 - Visual Basic Schneider1 Chapter 4 General Procedures.
Vahé Karamian Python Programming CS-110 CHAPTER 6 Defining Functions.
Python Functions.
Introduction to Computing Using Python for loop / def- ining a new function  Execution control structures ( if, for, function call)  def -ining a new.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Introduction to Computing Using Python Namespaces – Local and Global  The Purpose of Functions  Global versus Local Namespaces  The Program Stack 
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
Introduction to Computing Using Python Namespaces – Local and Global  The Purpose of Functions  Global versus Local Namespaces  The Program Stack 
Xiaojuan Cai Computational Thinking 1 Lecture 6 Defining Functions Xiaojuan Cai (蔡小娟) Fall, 2015.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
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.
VHDL Discussion Subprograms IAY 0600 Digital Systems Design Alexander Sudnitson Tallinn University of Technology 1.
Functions Functions, locals, parameters, and separate compilation.
8. DECISION STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(
Introduction to Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1.
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
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.
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Announcements Reading Read Chapter 4 (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.
CMSC201 Computer Science I for Majors Lecture 13 – Functions
Announcements Reading Project1 Codelab: Read Chapter 4 (functions)
Python: Experiencing IDLE, writing simple programs
Python Programming: An Introduction to Computer Science
A Lecture for the c++ Course
Chapter 6 Functions.
Functions CIS 40 – Introduction to Programming in Python
CSCI 161: Introduction to Programming Function
CMSC201 Computer Science I for Majors Lecture 10 – Functions (cont)
CMSC201 Computer Science I for Majors Lecture 14 – Functions (Continued) Prof. Katherine Gibson Based on concepts from:
5. Functions Rocky K. C. Chang 30 October 2018
Namespaces – Local and Global
Introduction to Value-Returning Functions: Generating Random Numbers
G. Pullaiah College of Engineering and Technology
15-110: Principles of Computing
答題分佈 Python Programming, 2/e.
Introduction to Computer Science
CSE 190p University of Washington Michael Ernst
九月九日憶山東兄弟 ~王維 獨在異鄉為異客, 每逢佳節倍思親。 遙知兄弟登高處, 遍插茱萸少一人。
Namespaces – Local and Global
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
Defining Functions.
Presentation transcript:

6. FUNCTIONS Rocky K. C. Chang October 4, 2015 (Adapted from John Zelle’s slides)

Objectives To understand why programmers divide programs up into sets of cooperating functions. To be able to define new functions in Python. To understand the details of function calls and parameter passing in Python. To write programs that use functions to reduce code duplication and increase program modularity.

Functions everywhere So far, we ’ ve seen three different types of functions: Our programs comprise a single function called main(). Built-in Python functions (e.g., print() ) Functions from the standard libraries ( math.sqrt() ) Why functions? Code reuse Easier to maintain (modularity) Facilitate solving a complex problem

Function definition The part of the program that creates a function is called a function definition. def ( ): E.g., def avg(n1, n2, n3): print((n1+n2+n3)/3) where n1, n2, n3 are formal parameters. A function is called/invoked by ( ) E.g., avg(1, 2, 3), where 1, 2 and 3 are actual parameters. Functions must be defined/imported before it is called.

EXERCISE 6.1 Try def avg(n1,n2,n3): print((n1+n2+n3)/3) avg(1, 2, 3) n1,n2,n3 = 10,20,10 avg(n1, n2, n3) What are the values of n1, n2, and n3?

Scope of formal parameters and variables Scope: places in a program where the parameters and variables are referenced. Formal parameters and all variables used in the function, are only accessible in the body of the function (i.e., they are local.) Variables with identical names elsewhere in the program are distinct from the formal parameters and variables inside of the function body.

EXERCISE 6.2 Visualize the following codes using Python tutor ( def avg(n1, n2, n3): print((n1 + n2 + n3)/3) n1, n2, n3 = 10, 20, 30 avg(n1, n2, n3) n1, n2, n3 = 100, 200, 300 print(n1, n2, n3)

Positional arguments A positional argument is an argument that is assigned to a particular parameter based on its position in the argument list. E.g., for exercise 6.2, the actual parameters n1/n2/n3 are passed to the formal parameters n1/n2/n3. A keyword argument is an argument that is specified by parameter name. E.g., def printNumbers(n1, n2, n3): print(n1, n2, n3) n1, n2, n3 = 10, 20, 30 printNumbers(n1=n2, n2=n3, n3=n1)

Default parameters A default argument is an argument that can be optionally provided in a given function call. When not provided, the corresponding parameter provides a default value. For example, the followings give the same outputs. print("The default print() parameters.") print("The default print() parameters.", end="\n") print("The default print() parameters.", sep=" ") print("The default print() parameters.", end="\n", sep=" ") print("The default print() parameters.", sep=" ", end="\n")

Functions making program branch After calling avg(1, 2, 3), the codes in avg() are executed. After avg() is executed, the program control goes back to the next statement after avg(1, 2, 3). That is, functions makes the execution of statements non- sequential. Therefore, the program must remember which is the next statement to execute (e.g., using a stack to remember it).

EXERCISE 6.3 Try import traceback def avg(n1, n2, n3): print((n1 + n2 + n3)) for line in traceback.format_stack(): print(line.strip()) n1, n2, n3 = 10, 20, 30 avg(1, 2, 3) n1, n2, n3 = 100, 200, 300 print(n1, n2, n3)

Stack traceback The Python traceback module: This module provides a standard interface to extract, format and print stack traces of Python programs. It exactly mimics the behavior of the Python interpreter when it prints a stack trace.

EXERCISE 6.4 Try import traceback def f(): g() def g(): for line in traceback.format_stack(): print(line.strip()) f()

Getting Results from a Function Passing parameters provides a mechanism for initializing the variables in a function. Parameters act as inputs to a function. The function may return the result through the return statement. E.g., def square(x): return x*x Inclusion of return is not necessary in Python.

EXERCISE 6.5 Try def fun(x): return; fun(2) def fun(x): return None; fun(2) def fun(x): ; fun(2) def fun(x): x; fun(2) def fun(x): a; fun(2)

EXERCISE 6.6 Try def fun(x): return; x = fun(2) def fun(x): return None; fun(2) def fun(x): return None; x = fun(2) def fun(x): x; x = fun(2) You could print x.

Returning multiple values Sometimes a function needs to return more than one value. To do this, simply list more than one expression in the return statement. E.g., def sumDiff(x, y): sum = x + y diff = x – y return sum, diff x, y = sumDiff(9, 8)

Functions that modify parameters Return values are the main way to send information from a function back to the caller. Sometimes, we can communicate back to the caller by making changes to the function parameters. For example, def addInterest(balance, rate): … amount = rate = 0.05 addInterest(amount, rate)

EXERCISE 6.7 Try whether this works. def addInterest(balance, rate): newBalance = balance * (1 + rate) balance = newBalance def test(): amount = rate = 0.05 addInterest(amount, rate) print("My current balance is: ", amount) test()

Behind the scene

EXERCISE 6.8 Will this work? def addInterest(balance, rate): balance = balance * (1 + rate) def test(): amount = rate = 0.05 addInterest(amount, rate) print("My current balance is: ", amount) test()

At the end Execution of addInterest() has completed and control returns to test(). The local variables, including the parameters, in addInterest() go away, but amount and rate in the test() function still refer to their initial values!

EXERCISE 6.9 Try the codes on the next slide. Is the result expected?

Another example 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()

Behind the scene

A few points Each value is given by multiple names (i.e., name aliasing) The old values have not changed, but the new values were created and assigned into the list. The old values will be destroyed during garbage collection. Will this work? def changeString(string): string[0] = "A" name = "RockyChang" changeString(name)

EXERCISE 6.10 Try def funList(aList): aList.append(1) aList = [2,3] L1 = [0] funList(L1) print(L1)

EXERCISE 6.11 Write a program that will generate a Celsius- Fahrenheit degree conversion program with the output like the one on the next page. But you are required to design and implement several functions that will make your program more modular.

Functions and Program Structure So far, functions have been used as a mechanism for reducing code duplication. Another reason to use functions is to make your programs more modular. As the algorithms you design get increasingly complex, it gets more and more difficult to make sense out of the programs.

END