Functions and abstraction Michael Ernst UW CSE 190p Summer 2012.

Slides:



Advertisements
Similar presentations
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Advertisements

CS 201 Functions Debzani Deb.
Introduction to Python
Python Programming Fundamentals
Introduction to Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
Introduction to Computational Linguistics Programming I.
Chapter 6 Functions -- QuickStart. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. What is a function?
Testing Michael Ernst CSE 140 University of Washington.
Computer Science 101 Introduction to Programming.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
This Week The string type Modules print statement Writing programs if statements (time permitting) The boolean type (time permitting)
Input, Output, and Processing
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
Functions, Procedures, and Abstraction Dr. José M. Reyes Álamo.
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 6 Defining Functions.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Functions and abstraction Michael Ernst UW CSE 140 Winter 2013.
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.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
1 CS161 Introduction to Computer Science Topic #9.
Python Functions : chapter 3
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Testing CSE 160 University of Washington 1. Testing Programming to analyze data is powerful It’s useless (or worse!) if the results are not correct Correctness.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
Language Find the latest version of this document at
1. COMPUTERS AND PROGRAMS Rocky K. C. Chang September 6, 2015 (Adapted from John Zelle’s slides)
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
PYTHON FUNCTIONS. What you should already know Example: f(x) = 2 * x f(3) = 6 f(3)  using f() 3 is the x input parameter 6 is the output of f(3)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
Introduction to Programming
Introduction to Python
Intro to Computer Science CS1510 Dr. Sarah Diesburg
© 2010 David A Watt, University of Glasgow
Functions and abstraction
Case Statements and Functions
Testing UW CSE 160 Winter 2017.
Variables, Expressions, and IO
Functions CIS 40 – Introduction to Programming in Python
Testing UW CSE 160 Spring 2018.
Functions and abstraction
Teaching London Computing
Testing UW CSE 160 Winter 2016.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
COMPUTER PROGRAMMING SKILLS
Introduction to Computer Science
CSE 190p University of Washington Michael Ernst
CISC101 Reminders Assignment 3 due today.
Rules of evaluation The value of a number is itself.
The Python interpreter
Michael Ernst UW CSE 190p Summer 2012
Class code for pythonroom.com cchsp2cs
Functions Taken from notes by Dr. Neil Moore & Dr. Debby Keen
def-ining a function A function as an execution control structure
 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.
Using Modules.
Defining Functions.
Lecture 2 - Names & Functions
Presentation transcript:

Functions and abstraction Michael Ernst UW CSE 190p Summer 2012

Functions In math, you use functions: sine, cosine, … In math, you define functions: f(x) = x 2 + 2x + 1 A function packages up and names a computation Enables re-use of the computation (generalization) Don’t Repeat Yourself (DRY principle) Shorter, easier to understand, less error-prone Python lets you use and define functions We have already seen some Python functions: – len, float, int, str, range

Using (“calling”) a function len(“hello”) len(“”) round(2.718) round(3.14) pow(2, 3) math.sin(0) math.sin(math.pi / 2) Some need no input: random.random() All produce output What happens if you forget the parentheses on a function call? random.random – Functions are values too – Types we know about: int, float, str, bool, list, function

A function is a machine You give it input It produces a result 2x + 1 x x x In math: func(x) = 2x + 1

Creating a function Define the machine, including the input and the result def func(x): return 2*x + 1 Keyword that means: I am def ining a function Keyword that means: This is the result Input variable name, or “formal parameter” Name of the function. Like “x = 5” for a variable 2x + 1 x Return expression (part of the return statement)

More function examples def square(x): return x * x def fahr_to_cent(fahr): return (fahr – 32) / 9.0 * 5 def cent_to_fahr(cent): result = cent / 5.0 * return result def print_hello(): print “Hello, world” def print_fahr_to_cent(fahr): result = fahr_to_cent(fahr) print result def abs(x): if x < 0: return – x else: return x Define the machine, including the input and the result Returns the value None

Digression: Two types of output An expression evaluates to a value – Which can be used by the rest of the program A print statement writes text to the screen The Python interpreter (command shell) reads statements and expressions, then executes them If the interpreter executes an expression, it prints its value In a program, evaluating an expression does not print it In a program, printing an expression does not permit it to be used elsewhere

Formal parameter (a variable) How Python executes a function call 1.Evaluate the argument (at the call site) 2.Assign the formal parameter name to the argument’s value – A new variable, not reuse of any existing variable of the same name 3.Evaluate the statements in the body one by one 4.At a return statement: – Remember the value of the expression – Formal parameter variable disappears – exists only during the call! – The call expression evaluates to the return value def square(x): return x * x square(3 + 4) Function definition Function call or function invocation Current expression: 1 + square(3 + 4) 1 + square(7) Variables: x: 7 return x * x return 7 * x return 7 * 7 return 49 evaluate this expression Actual argument

Examples of function invocation def square(x): return x * x Variables: square(3) + square(4) (none) return x * x x: 3 return 3 * x x: 3 return 3 * 3 x: 3 return 9 x: square(4) (none) return x * x x: 4 return 4 * x x: 4 return 4 * 4 x: 4 return 16 x: (none) 25 (none)

Examples of function invocation def fahr_to_cent(fahr): return (fahr – 32) / 9.0 * 5 def cent_to_fahr(cent): return cent / 5.0 * Variables: fahr_to_cent(cent_to_fahr(20)) (none) return cent / 5.0 * cent: 20 return 20 / 5.0 * cent: 20 return 68 cent: 20 fahr_to_cent(68) (none) return (fahr – 32) / 9.0 * 5 fahr: 68 return (68 – 32) / 9.0 * 5 fahr: 68 return 20 fahr: (none)

Examples of function invocation def square(x): return x * x Variables: square(square(3)) (none) return x * x x: 3 return 3 * x x: 3 return 3 * 3 x: 3 return 9 x: 3 square(9) (none) return x * x x: 9 return 9 * x x: 9 return 9 * 9 x: 9 return 81 x: 9 81 (none)

Examples of function invocation def square(z): return z*z def hypotenuse(x, y): return math.sqrt(square(x) + square(y)) Variables: hypotenuse(3, 4) (none) return math.sqrt(square(x) + square(y)) x: 3 y:4 return math.sqrt(square(3) + square(y)) x: 3 y:4 return z*z z: 3 x: 3 y:4 return 3*3 z: 3 x: 3 y:4 return 9 z: 3 x: 3 y:4 return math.sqrt(9 + square(y)) x: 3 y:4 return math.sqrt(9 + square(4)) x: 3 y:4 return z*z z: 4 x: 3 y:4 return 4*4 z: 4 x: 3 y:4 return 16 z: 4 x: 3 y:4 return math.sqrt(9 + 16) x: 3 y:4 return math.sqrt(25) x: 3 y:4 return 5 x: 3 y:4 5 (none)

Examples of function invocation def square(x): return x*x def hypotenuse(x, y): return math.sqrt(square(x) + square(y)) Variables: hypotenuse(3, 4) (none) return math.sqrt(square(x) + square(y)) x: 3 y:4 return math.sqrt(square(3) + square(y)) x: 3 y:4 return x*x x: 3 x: 3 y:4 return 3*3 x: 3 x: 3 y:4 return 9 x: 3 x: 3 y:4 return math.sqrt(9 + square(y)) x: 3 y:4 return math.sqrt(9 + square(4)) x: 3 y:4 return x*x x: 4 x: 3 y:4 return 4*4 x: 4 x: 3 y:4 return 16 x: 4 x: 3 y:4 return math.sqrt(9 + 16) x: 3 y:4 return math.sqrt(25) x: 3 y:4 return 5 x: 3 y:4 5 (none)

Examples of function invocation def square(x): return x*x def hypotenuse(x, y): return math.sqrt(square(x) + square(y)) Variables: hypotenuse(3, 4) (none)hypotenuse() return math.sqrt(square(x) + square(y)) x: 3 y:4 return math.sqrt(square(3) + square(y)) square()x: 3 y:4 return x*x x: 3 x: 3 y:4 return 3*3 x: 3 x: 3 y:4 return 9 x: 3 x: 3 y:4 return math.sqrt(9 + square(y)) x: 3 y:4 return math.sqrt(9 + square(4)) square()x: 3 y:4 return x*x x: 4 x: 3 y:4 return 4*4 x: 4 x: 3 y:4 return 16 x: 4 x: 3 y:4 return math.sqrt(9 + 16) x: 3 y:4 return math.sqrt(25) x: 3 y:4 return 5 x: 3 y:4 5 (none)

In a function body, assignment creates a temporary variable (like the formal parameter) stored = 0 def store_it(arg): stored = arg return stored print store_it(22)# prints 22 print stored# prints 0 Global or Variables: top level print store_it(22) store_it()stored: 0 stored = arg; return stored x: 22stored: 0 stored = 22; return stored x: 22stored: 0 return stored x: 22 stored: 22stored: 0 return 22 x: 22 stored: 22stored: 0 print 22 stored: 0 print stored stored: 0

A variable use finds the nearest variable of the given name Looking up a global variable works if no local of the same name exists x = 22 stored = 100 def lookup(): x = 42 return stored + x lookup() x = 5 stored = 200 lookup()

Abstraction Abstraction = ignore some details Generalization = become usable in more contexts Abstraction over computations: – functional abstraction, a.k.a. procedural abstraction As long as you know what the function means, you don’t care how it computes that value – You don’t care about the implementation (the function body)

Defining absolute value def abs(x): if val < 0: return -1 * val else: return 1 * val def abs(x): if val < 0: return - val else: return val def abs(x): if val < 0: result = - val else: result = val return result def abs(x): return math.sqrt(x*x)

Defining round (for positive numbers) def round(x): return int(x+0.5) def round(x): fraction = x-int(x) if fraction >=.5: return int(x) + 1 else: return int(x)

For programmers: arbitrary text after # For users: a string as the first element of the function body Two types of documentation 1.Documentation for users/clients/callers – Document the purpose or meaning or abstraction that the function represents – Tells what the function does – Should be written for every function 2.Documentation for programmers who are reading the code – Document the implementation – specific code choices – Tells how the function does it – Necessary for tricky or interesting bits of the code def square(x): """Returns the square of its argument.""" # “x*x” can be more precise than “x**2” return x*x

Multi-line strings New way to write a string – surrounded by three quotes instead of just one – "hello" – 'hello' – """hello""" – '''hello''' Any of these works for a documentation string Triple-quote version can include newlines (carriage returns), so the string can span multiple lines

Don’t write useless comments Comments should give information that is not apparent from the code Here is a counter-productive comment that merely clutters the code, which makes it harder to read: # increment the value of x x = x + 1

Where to write comments By convention, write a comment above the code that it describes (or, more rarely, on the same line) – First, a reader sees the English intuition or explanation, then the possibly-confusing code # The following code is adapted from # “Introduction to Algorithms, by Cormen et al., # section while (n > i):... A comment may appear anywhere in your program, including at the end of a line: x = y + x # a comment about this line For a line that starts with #, indentation must be consistent with surrounding code