PHYTON
PHYTON
Examples
>>> convert_to_celsius(32)
0
>>> convert_to_celsius(212)
100
Type Contract
(number) -> number
Header
def convert_to_celsius(fahrenheit):
Description
Return the number of Celsius degrees equivalent to fahrenheit degrees.
Body
return (fahrenheit - 32) * 5 / 9
Test
Run the examples.
>>> convert_to_ccelsius(32)
0
>>> convert_to_celsius(212)
100
'''
return (fahrenheit - 32) * 5 / 9
Function Reuse
Calling functions within other function definitions
The problem: Calculate the semi-perimeter of a triangle.
>>> perimeter(3, 4, 5)
12
>>> perimeter(10.5, 6, 9.3)
25.8
'''
return side1 + side2 + side3
>>> semiperimeter(3, 4, 5)
6.0
>>> semiperimeter(10.5, 6, 9.3)
12.9
'''
return perimeter(side1, side2, side3) / 2
Calling functions within other function calls
The problem: One triangle has a base of length 3.8 and a height of length 7.0. A
second triangle has a base of length 3.5 and a height of length 6.8. Calculate
which of two triangles' areas is biggest.
The approach: Pass calls to function area as arguments to built-in function max.
def convert_to_minutes(num_hours):
"""(int) -> int
Return the number of minutes there are in num_hours hours.
>>> convert_to_minutes(2)
120
"""
result = num_hours * 60
return result
def convert_to_seconds(num_hours):
"""(int) -> int
Return the number of seconds there are in num_hours hours.
>>> convert_to_seconds(2)
7200
"""
return convert_to_minutes(num_hours) * 60
seconds_2 = convert_to_seconds(4)
Here is what the memory model looks like just before the return statement inside
function convert_to_minutes looks like:
Here is a link to the Python Visualizer at this stage of the execution so that you
can explore this yourself. We strongly encourage you to step backward and forward
through this program until you understand every step of execution.
When the return statement is executed, the call on convert_to_minutes exits. The
bottom stack frame is removed, and execution resumes using the stack frame for
convert_to_seconds: