LECTURE 15 Introduction to Functions. Informal idea of a function  A function converts an input to an output  The inputs are called actual parameters.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

1.1 Line Segments, Distance and Midpoint
UNIT-1 Bresenham’s Circle Algorithm
Unit-iv.
Introduction to Algorithms
Calculating Slope m = y2 – y1 x2 – x1.
SI23 Introduction to Computer Graphics
Learning Objectives for Section 3.2
Chapter 7: Arrays In this chapter, you will learn about
Simple Interest Lesson
Graphing Lines Day 0ne. Cover the concepts: Relation Function
Math in Our World Section 8.2 Simple Interest.
COORDINATE PLANE.
CS 240 Computer Programming 1
Section 5.1 – Exponential Functions and Their Graphs.
Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
1 Lecture 16:User-Definded function I Introduction to Computer Science Spring 2006.
Quiz Number 2 Group 1 – North of Newark Thamer AbuDiak Reynald Benoit Jose Lopez Rosele Lynn Dave Neal Deyanira Pena Professor Kenneth D. Lawerence New.
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 8 Fruitful Functions 05/02/09 Python Mini-Course: Day 2 - Lesson 8 1.
Python Programming Chapter 5: Fruitful Functions Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
2/7/2008. >>> Overview * boolean * while * random * tuples.
CS107 Introduction to Computer Science Lecture 3, 4 An Introduction to Algorithms: Loops.
Saving and Interest February Saving and Interest An Equation to define Savings: – SAVING = Disposable Income – Consumption. Interest: – Simple Interest.
CONTINUOUSLY COMPOUNDED INTEREST FORMULA amount at the end Principal (amount at start) annual interest rate (as a decimal) time (in years)
Learning Objectives for Sections Simple & Compound Interest
What is Interest? Interest is the amount earned on an investment or an account. Annually: A = P(1 + r) t P = principal amount (the initial amount you borrow.
CS107 Introduction to Computer Science Lecture 5, 6 An Introduction to Algorithms: List variables.
Algorithms. Introduction Before writing a program: –Have a thorough understanding of the problem –Carefully plan an approach for solving it While writing.
3-3 Example 1 Find the simple interest earned on an investment of $500 at 7.5% for 6 months. 1. Write the simple interest formula. I = prt Lesson 3-3 Example.
Fruitful functions. Return values The built-in functions we have used, such as abs, pow, int, max, and range, have produced results. Calling each of these.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Course A201: Introduction to Programming 11/04/2010.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Chapter 1. Objectives To provide examples of computer science in the real world To provide an overview of common problem- solving strategies To introduce.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
Lesson 7.6 Concept: How to find simple interest Guidelines: When you compute simple interest for a time that is less than 1year, write the time as a fraction.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
ITP © Ron Poet Lecture 7 1 Repetition. ITP © Ron Poet Lecture 7 2 Easing Repetitive Tasks  Many computing task are repetitive.  Checking all known foods.
Java™ How to Program, Early Objects Version, 8/e © by Pearson Education, Inc. All Rights Reserved.
Simple Interest Formula I = PRT. I = interest earned (amount of money the bank pays you) P = Principle amount invested or borrowed. R = Interest Rate.
17 November 2015Birkbeck College1 Introduction to Computer Systems Lecturer: Steve Maybank Department of Computer Science and Information Systems
Math – Solving Problems Involving Interest 1.
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
You deposit $950 into an account that earns 4 % interest compounded annually. Find the balance in the account after five years. In your last calculation,
Bellringer Calculate the Simple Interest for #s 1 and 3 and the Total cost for #2. 1.$1800 at 3.2% for 4 years. 2. $17250 at 7.5% for 6 years. 3. $3,650.
1 CSC103: Introduction to Computer and Programming Lecture No 16.
Challenging… Interest Rates and Savings By: Nicole Sandal.
Lecture 14 – lists, for in loops to iterate through the elements of a list COMPSCI 1 1 Principles of Programming.
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
Lesson 4: Introduction to Control Statements 4.1 Additional Operators Extended Assignment Operators –The assignment operator can be combined with the.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
Simple Interest The simple interest formula is often abbreviated in this form: I = P R T Three other variations of this formula are used to find P, R and.
Introduction to Programming
8.3 Compound Interest HW: (1-21 Odds, Odds)
Chapter 4 C Program Control Part I
Topics Introduction to Repetition Structures
SIMPLE AND COMPOUND INTEREST
CHAPTER 1 Introduction.
Simple and Compound Interest
Practice with loops! What is the output of each function below?
Topics Introduction to Repetition Structures
What does this do? def revList(L): if len(L) < = 1: return L x = L[0] LR = revList(L[1:]) return LR + x.
Introduction to Programming
Python Basics with Jupyter Notebook
National Central University, Taiwan
Compounded and Continuous Interest
Introduction to Programming
Lecture 6 - Recursion.
Presentation transcript:

LECTURE 15 Introduction to Functions

Informal idea of a function  A function converts an input to an output  The inputs are called actual parameters or arguments  The output is called the return value. Input function output

Examples

Name: maxOf2  Input: two numbers  Output: the value of the largest one  Defining the function in Python def maxOf2(n1, n2): # n1 and n2 are numbers #returns the largest if n1 >= n2: return n1 else: return n2

Using the function # Using a variable to “catch” the returned value ans = maxOf2(48, 35) print ans ans1 =maxOf2(45.6, 78.3) print ans1 # Printing the returned value immediately # Note that sometimes the function may work for values of the actual # parameters that were not intended! Don’t count on it! print maxOf2("Dan", "Don") print maxOf2([1,2,3], [4,5,6])

Maximum number in a list  Input: a list of numbers  Output: the value of the largest number in the list  Algorithm:

Maximum number in a list  Input: a list of numbers  Output: the value of the largest number in the list  Algorithm:  Let biggestSoFar be the first item in the list  Loop through all items in the list If you find some item larger than biggestSoFar, set biggestSoFar to this new value

#Defining the function in Python def maxInList(aList): #aList is a non empty list of numbers #returns the largest item on the list biggestSoFar = aList[0] for item in aList[1:]: if item > biggestSoFar: biggestSoFar = item return biggestSoFar #Using the function #A variable to “catch” the returned value ans = maxInList( [2,65,98,44,5,21,50,64]) print ans #Using the returned value directly print maxInList( ['Hal', 'Sally', 'George', 'Tim', 'Mike'])

Compute simple interest  Input: Principal, rate, years  Output: The amount of interest earned on the principal after the given number of years  Defining the function in Python

def simpleInterest(principal, rate, years): #rate is given as a decimal so a 2% annual rate #would be given as 0.02 #Returns the total amount of interest on the principate at rate #for this many years interest = principal*rate*years return interest #Using the function in Python print simpleInterest(500, 0.03, 5)

Compound Interest  Input: principal, annual rate, number of compounding periods per year, number of years  Output: The total interest earned  Algorithm:  Figure out the rate per compounding period  Figure out the number of compounding periods  Compute the final value of the investment  Compute and return the interest

#Defining the function in Python def compoundInterest(principal, rate, n, years): #returns the interest gained on the principal after years #where the interest is compounded n times per year #rate is the annual rate given as a decimal #compute the number of compounding periods p = n * years #compute the interest rate per compounding period r = rate/n #calculate the final value of the investment value = principal for i in range(p): value = value + value*r #calculate the difference between the initial investment and #the current value interest = value - principal return interest #Using the function in Python print compoundInterest(500,0.03,12,5)

Find the distance between points  Input: Two points (given as graphics objects)  Output: The distance between the points  Algorithm:

Find the distance between points  Input: Two points (given as graphics objects)  Output: The distance between the points  Algorithm:  Find the x and y coordinates of the first point  Find the x and y coordinate of the second point  Use the distance formula to calculate the distance  Return the distance

#Define the function def distance(p1, p2): #p1 and p2 are Point objects #returns the distance between the points x1 = p1.getX() y1 = p1.getY() x2 = p2.getX() y2 = p2.getY() dist = math.sqrt( (x1 - x2)**2 + (y1 - y2)**2) return dist #Use the function print distance(Point(3,4), Point(0,0))

Tell if point is inside a circle  Input: Point object and Circle object  Output: True or False depending on whether the point is inside the circle  Algorithm

Tell if point is inside a circle  Input: Point object and Circle object  Output: True or False depending on whether the point is inside the circle  Algorithm  Get the center of the circle  Get the radius of the circle  Calculate the distance of the point to the center of the circle  If it is less that the radius return True  Otherwise return False

#Defining the function def isInside(myPoint, myCircle): #returns True if myPoint is inside myCircle; otherwise False p1 = myCircle.getCenter() r = myCircle.getRadius() dis = distance(myPoint,p1) #use the other function I defined if dis <=r: return True else: return False #Using the function win = GraphWin("Testing Functions", 400, 400) win.setCoords (0,0,5,5) c = Circle(Point(2,3), 0.5) c.draw(win) c.setFill("yellow") p1 = Point(2,4) p1.draw(win) print isInside(p1, c)

Make a circle “blink” in new color  Input: a Circle object, the current color, a new color  Output: Nothing to return  Algorithm

Make a circle “blink” in new color  Input: a Circle object, the current color, a new color  Output: Nothing to return  Algorithm  set fill to new color  Sleep for one minute  Set fill to the original color

def flash (myCircle, oldColor, newColor): #expects a circle whose fillColor is oldColor #changes the color of myCircle to new color, waits 1 sec\ #and changes back to old color myCircle.setFill(newColor) time.sleep(1) myCircle.setFill(oldColor) return win = GraphWin("Testing Functions", 400, 400) win.setCoords (0,0,5,5) c = Circle(Point(2,3), 0.5) c.draw(win) c.setFill("yellow") p1 = Point(2,4) p1.draw(win) print isInside(p1, c) flash(c, "yellow", "green") time.sleep(1) flash(c, "yellow", 'pink')