Structuring Computer Programs
Python comes with many built-in functions, some of which you may have seen before:
When creating a program to perform a particular task it is often useful to decompose a large problem into several smaller parts that are easier to understand and test.
Consider how to make a peanut butter & jelly sandwich:
Python functions are declared using the def keyword followed by the name for your function. After the name is a set of parentheses containing an optional list of parameters, followed by a colon, which begins the block of your function.
Python functions usually return a value. For example here’s a function that calculates the area of a circle using a radius parameter that is passed in:
1256.63168
A function can contain multiple statements. Here’s a function that calculates the number seconds in a given number of years.
43800
Can you modify the hours_in_year function to return the seconds in a year:
Modify the hours_in_year function to return the seconds in a year:
def seconds_in_year(year):
days = year * 365
hours = days * 24
minutes = hours * 60
seconds = minutes * 60
return seconds
print(seconds_in_year(3))
94608000
Python comes with lots of functions that are organized into modules, which we’ll be talking about later in the semester.
31