Matthew Hrehirchuk, Eric Chalmers, Charlotte Curtis, Patrick Perri
Section4.6Decoding a Function
In general, when you see a function definition you will try figure out what the function does, but, unless you are writing the function, you won’t care how it does it (recall abstraction).
int takes one parameter. It can be of any type that can be converted into an integer, such as a floating point number or a string whose characters are all digits.
Sometimes, you will be presented with a function definition whose operation is not so neatly summarized as above. Sometimes you will need to look at the code, either the function definition or code that invokes the function, in order to figure out what it does. (Consider practicing this by looking up the printfunctions docstring.)
If you try to make use of functions, ones you write or that others write, without being able to answer these questions, you will find that your debugging sessions are long and painful.
The first question is always easy to answer. Look at the line with the function definition, look inside the parentheses, and count how many variable names there are.
The second and third questions are not always so easy to answer. In Python, unlike some other programming languages, variables are not declared to have fixed types, and the same holds true for the variable names that appear as formal parameters of functions. You have to figure it out from context.
To figure out the types of values that a function expects to receive as parameters, you can look at the function invocations or you can look at the operations that are performed on the parameters inside the function.
a built in function, look at its docstring to see what it requires and what it returns. For example, len(x), must be passed a sequence data type like a string and will return an integer. x can’t be a number or a Boolean.
"""
Calculates the combined areas of two squares.
Parameters:
width_a : _____
The width of the first square.
width_b : _____
The width of the second square.
Returns:
_____ : The combined areas of the squares.
"""
Since both pieces of data are integers, and the formula for calculating the area of a square wouldn’t result in a float given an integer, this would be correct.
Based on the formula for finding the area of a square, and that no rounding is present, by giving this function two floats, an integer would not be returned.
Based on the formula for finding the area of a square, and that the widths are only being multiplied, by giving this function two integers, a float could not be returned.
Since both pieces of data are floats, and the formula for calculating the area of a square would result in a float given a float, this would be correct.