COSC 1306—COMPUTER SCIENCE AND PROGRAMMING PYTHON FUNCTIONS Jehan-François Pâris

Slides:



Advertisements
Similar presentations
This Week More Types boolean string Modules print statement Writing programs if statement Type boolean.
Advertisements

Chapter Five Functions
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Structured programming
Math class methods & User defined methods Math class methods Math.sqrt(4.0) Math.random() java.lang is the library/package that provides Math class methods.
 2007 Pearson Education, Inc. All rights reserved C Functions.
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.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Introduction to Computers and Programming Lecture 13: User defined methods Instructor: Evan Korth New York University.
Functions and abstraction Michael Ernst UW CSE 190p Summer 2012.
 2003 Prentice Hall, Inc. All rights reserved Introduction Modules –Small pieces of a problem e.g., divide and conquer –Facilitate design, implementation,
COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
Programming Training Main Points: - Python Statements - Problems with selections.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
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.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Functions, Procedures, and Abstraction Dr. José M. Reyes Álamo.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Methods (a.k.a. Functions)
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
Topics: IF If statements Else clauses. IF Statement For the conditional expression, evaluating to True or False, the simple IF statement is if : x = 7.
Simple Functions and Names Sec 9-4 Web Design. Objectives The student will: Know how to create a simple function in Python. Know how to call a function.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 6 Defining Functions.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions Outline 5.1Introduction 5.2Program Modules.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 5 JavaScript.
CS212: Object Oriented Analysis and Design
COSC 1306 COMPUTER SCIENCE AND PROGRAMMING Jehan-François Pâris
Python Functions : chapter 3
Loops and Simple Functions CS303E: Elements of Computers and Programming.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
2.1 Functions. Functions in Mathematics f x y z f (x, y, z) Domain Range.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Introduction to Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Loops and Simple Functions COSC Review: While Loops Typically used when the number of times the loop will execute is indefinite Typically used when.
© Peter Andreae Java Programs COMP 102 # T1 Peter Andreae Computer Science Victoria University of Wellington.
Dale Roberts CSCI N305 Functions Declarations Department of Computer and Information Science, School of Science, IUPUI.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 9 Functions.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
COSC 1306 COMPUTER SCIENCE AND PROGRAMMING
Introduction to Python
Functions CIS 40 – Introduction to Programming in Python
Deitel- C:How to Program (5ed)
Functions.
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
Chapter 5 - Functions Outline 5.1 Introduction
Functions Declarations CSCI 230
Functions, Procedures, and Abstraction
Topic 1: Problem Solving
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Introduction to Value-Returning Functions: Generating Random Numbers
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
COSC 1306 COMPUTER SCIENCE AND PROGRAMMING
Loops and Simple Functions
COMPUTER PROGRAMMING SKILLS
Introduction to Computer Science
Functions, Procedures, and Abstraction
 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.
Presentation transcript:

COSC 1306—COMPUTER SCIENCE AND PROGRAMMING PYTHON FUNCTIONS Jehan-François Pâris

INTRODUCTION

Computing the square root (I) Want a simple algorithm to compute √s of a positive number. If x = √ s then x 2 = s and x = s/ x Consider an approximation a of √ s – If a √s – If a > √ s then s/a < √s In either case, √ s is between a and s/a

Computing the square root (I) The average of a and s/a ( a + s/a )/2 is a better estimate of √s 0a s/a s is inside If a < s 0s/a a s is inside If a > s

Computing √ 5 Find root of5 Approximations as/aAverage ………

New Problem When should we end? –When our result is accurate enough –When the interval (s, s/a) is small enough Checking s – s/a < epsilon will not work

New Problem When should we end? –When our result is accurate enough –When the interval (s, s/a) is small enough Checking s – s/a < epsilon will not work because s – s/a can be negative Must check abs(s – s/a) < epsilon

First attempt s = float(input("Enter a positive number: ")) a = 1 sovera = s/a print("Root is between %.3f and %.3f" % (s, a, sovera)) while abs(a - sovera) > 10e-6 : a = (a + sovera)/2 sovera = s/a print("The square root of %.6f is %.6f" % (s, approximation))

Criticism Two big issues –We normally need to compute a square root inside another computation Make it a function "square root" –We do not let the user specify the precision Should let the user enter it

Second attempt def mysqrt (s) : a = 1 sovera = s/a while abs(a - sovera) > 10e-6 : a = (a + sovera)/2 sovera = s/a return a n = float(input("Enter a positive number: ")) answer = mysqrt(n) print("The square root of %.6f is %.6f" % (number, answer))

Explanations Function is defined—or declared—within –def function_name(parameter_list) : … return(…) return specifies which values should be returned by a function –A function can have several return statements

Example """Maximum of two numbers """ def mymax(a, b) : if a > b : return a else : return b

Third attempt """ Square root with arbitrary precision """ def mysqrt (s, epsilon) : a = 1 sovera = s/a while abs(a - sovera) > epsilon : a = (a + sovera)/2 sovera = s/a return a

Criticism Not everybody wants to specify a precision –Should make it optional

Fourth attempt """ Square root with arbitrary precision """ def mysqrt (s, epsilon = ) : a = 1 sovera = s/a while abs(a - sovera) > epsilon : a = (a + sovera)/2 sovera = s/a return a

FUNCTIONS

Built-in functions print(…) is always available Other functions are parts of modules – sqrt(…) is part of math module Before using any of these functions we must import them – from math import sqrt – from random import randint, uniform Don't forget the comma!

More about modules We can write our own modules –Can be situations where two or more modules have functions with the same names –Solution is to import the modules import math Can now use all functions in module –Must prefix them with module name math.sqrt(…)

Your two choices When you want to use the function sqrt( ) from the module math, you can either use – from math import sqrt and refer directly to sqrt( ) – import math and refer to the function as math.sqrt()

Good practice rules Put all your import and use statements at the beginning of your program –Makes the program more legible As soon as you use several modules, avoid import from ….. –Easier to find which function comes from which module

Writing your own function Very easy Write – def function_name ( parameters ) : statements return result Observe the column and the indentation REQUIRED!

What it does Function Parameters Result

Example >>> def maximum (a, b) : if a >= b : max = a else : max = b return max >>> maximum (2, 3) 3

Example >>> maximum(2.0, 3) 3 >>> maximum("big", "tall") 'tall' >>> maximum('big', 'small') 'small' >>> maximum ('a', 3) Does not work: unorderable types: str() >= int()

Multiple return statements >>> def maximum2 (a, b) : if a >= b : return a else : return b >>> maximum2(0, -1) 0

No return statement def goodbye() : input('Hit return when you are done.') >>> goodbye() Hit return when you are done. >>>>>> goodbye

These pesky little details The first line of the function declaration –Starts with the keyword def –Ends with a column Don’t forget the parentheses when you call a function – goodbye()

A second example (I) #firstfunctions.py """ This program contains two functions that convert C into F and F into C ""“ def celsius (temperature) : return (temperature - 32)*5/9 def fahrenheit (temperature) : return (temperature*9/5 + 32)

A second example (II) degrees = float(input('Enter a temperature: ')) print('%.1f Fahrenheit is same as' % degrees + ' %.1f Celsius' % celsius(degrees)) print('%.1f Celsius is same as' % degrees + ' %.1f Fahrenheit' % fahrenheit(degrees)) input('Hit return when you are done')

Creating a module Put the functions in a separate file #twofunctions.py """ This module contains two functions ""“ def celsius (temperature) : return (temperature - 32)*5/9 def fahrenheit (temperature) : return (temperature*9/5 + 32)

Using a module #samefunctions.py """ This program calls two functions. ""“ from twofunctions import celsius, fahrenheit degrees = float(input('Enter a temperature: ')) …

These pesky little details Module name must have.py suffix import statement should contain module name stripped of that suffix

Parameters w/ default values >>> def aftertax( price, taxrate = ) : return price*(1 + taxrate) >>> aftertax(100) >>> aftertax(100, 0) 100 >>> aftertax(200, 12) 224

Why you should write functions Makes your code more readable –Hides the details –Keeps each piece of code shorter Allows you to reuse your work