Download presentation
1
Python Functions : chapter 3
From Think Python How to Think Like a Computer Scientist
2
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) returned value is now an integer >>>float(45) returns a float >>>str(456) ‘456’
3
Mathematical Functions
>>> import math >>> math.sqrt(45) >>> r=5 >>>3/4.0*math.pi*r** >>> math.log(100,2) log of 100 base >>> math.sin(math.pi) e-16 what in the world is this? Study the trig example in exercise 3
4
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) >>> output that you’ve seen before
5
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 body Function definition Value to return Use four spaces for the indention
6
Function to find the area of a triangle
See Herons formula ( # 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) >>>
7
Function flow of execution
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 Be sure and define your functions before you use them!
8
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 >>> 25 2
9
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 Write a function to return the volume of a sphere of radius r 𝒗=𝟒/𝟑𝝅 𝒓 𝟑
10
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.