PythonFunctionsChap3

Download Report

Transcript PythonFunctionsChap3

PYTHON
FUNCTIONS : CHAPTER 3
FROM
THINK PYTHON
HOW TO THINK LIKE A COMPUTER SCIENTIST
TYPE CONVERSION
FUNCTIONS
A function in Python is a named sequence of instructions
that perform a computation. When a function is called it
returns the result of this computation.
>>> type ( 23.4)
<class ‘float’)>
returned value
>>> int(23.4)
23 returned value is now an integer
>>>float(45)
45.0
returns a float
>>>str(456)
‘456’
MATHEMATICAL
FUNCTIONS
>>> import math
>>> math.sqrt(45)
6.708203932499369
>>> r=5
>>>3/4.0*math.pi*r**3
294.5243112740431
>>> math.log(100,2)  log of 100 base 2
6.643856189774725
>>> math.sin(math.pi)
1.2246467991473532e-16
what in the world is this?
Study the trig example in exercise 3
NEW FUNCTIONS YOU WRITE
Type in the following script within the editor and run it
import math
def vol_of_sphere(radius):
 : is REQUIRED
vol = 4/3.0*math.pi*radius**3  indention is required
return vol
print vol_of_sphere(5)
>>>
523.598775598
>>>
 output that you’ve seen before
FUNCTION PARTS
Argument(sent in)
radius is called a
parameter.
def vol_of_sphere(radius):
header
vol = 4/3.0*math.pi*radius**3
return vol
Function definition
Value to return
Use four spaces for the indention
body
FUNCTION TO FIND THE
AREA OF A TRIANGLE
See Herons formula
(http://mathworld.wolfram.com/HeronsFormula.html)
# Herons formula as a script
import math
def area(a, b, c):
“”” a, b and c are the sides of a triangle “””  function info
s = 1/2.0*(a+b+c)
a = math.sqrt(s*(s-a)*(s-b)*(s-c))
return a
print area(1,1,1)
>>>
0.433012701892
>>>
FUNCTION FLOW OF
EXECUTION
Inst
Inst
Inst
Inst
print area(5,5,6)
def area(a, b, c):
s = 1/2.0*(a+b+c)
a = math.sqrt(s*(s-a)*(s-b)*(s-c))
return a
Inst
Inst
Inst
Be sure and define your functions before you use them!
FUNCTION VARIABLES AND
PARAMETERS ARE LOCAL
import math
#Define the function here
def area(a, b, c):
""" a, b and c are the sides of a triangle """
s = 1/2.0*(a+b+c)
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
return area
#The linear part of this program starts here
s = 25
a=2
print area(1,1,1)
print s,a
#here is the output
>>>
0.433012701892
25 2
>>>
IN CLASS PROBLEM
1. Write a function called FtoC that will convert Fahrenheit to
Celsius. You will need a single parameter. Run the program
to test it with some know values.
C = 5/9(F -32)
F=9/5C + 32
2. Write a function to return the volume of a sphere of radius r
𝒗 = 𝟒/𝟑𝝅𝒓𝟑
WHY FUNCTIONS?
• Lets you name a group of statements, which makes your
program easier to read.
• Functions make programs smaller by being able to reuse
the same code.
• Dividing programs into functions allow you to debug
sections at a time.
• Well defined functions can be used in other programs that
you write.
####################################################
Note: if you do this from math import * instead of import
math you will not need to include the math. prefix