Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "COSC 1306—COMPUTER SCIENCE AND PROGRAMMING PYTHON FUNCTIONS Jehan-François Pâris"— Presentation transcript:

1 COSC 1306—COMPUTER SCIENCE AND PROGRAMMING PYTHON FUNCTIONS Jehan-François Pâris jfparis@uh.edu

2 INTRODUCTION

3 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

4 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

5 Computing √ 5 Find root of5 Approximations as/aAverage 153 31.66672.3333 2.14292.2381 2.23402.2361 ………

6 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

7 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

8 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))

9 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

10 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))

11 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

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

13 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

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

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

16 FUNCTIONS

17 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!

18 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(…)

19 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()

20 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

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

22 What it does Function Parameters Result

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

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

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

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

27 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()

28 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)

29 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')

30 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)

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

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

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

34 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


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

Similar presentations


Ads by Google