Parameters and Arguments¶
The function greeting()
defined above is not vary useful, for a few reasons. In particular, it doesn’t accept any inputs. There are occassions when you will want to write functions that take no inputs, but functions are generally more useful when we are able to supply them information that affects how they behave.
When defining a function, we can specify that a function expects one or more inputs by listing variable names between the parentheses to serve as placeholders for the inputs. The placeholders themselves are called parameters, and specific values that are supplied as inputs are referred to as arguments.
In the example below, we create a function square()
that has a single parameter, denoted by n
. When the function is called, an argument must be supplied as a value for this parameter. The function will then print the square of that argument.
def square(n):
print(n**2)
In the cell below, we call the square
function with several different arguments. Each one of these arguments is substituted in for the parameter n
for that particular function call.
square(2)
square(3.6)
square(-3)
4
12.96
9
If we would like, we can specify the name of the parameter when we are calling a function. This is usually not necessary, however.
square(n=4)
16
Note that (unlike many languages) Python does not ask us to specifiy what data type the arguments should be. However, if we supply an argument for which the function would perform an illegal operation, we will get an error.
square('circle')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-aafa7e540230> in <module>
----> 1 square('circle')
<ipython-input-1-3e7f8c3e48a6> in square(n)
1 def square(n):
----> 2 print(n**2)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
Additionally, if a function has one or more parameters, but we don’t supply arguments for those parameters when we call the function, we will get an error.
square()