def square(x):
x_squared = x * x
print('the square of',x,'is',x_squared)
We 'call' this function using its name, followed by round brackets containing the value to be squared:
square(3)
square(5)
square(276)
the square of 3 is 9 the square of 5 is 25 the square of 276 is 76176
The variable x is an 'argument' to the function square. Arguments take on the value given when the function is used. Functions can have multiple arguments:
def maximum(a,b,c):
if a >= b and a >= c:
print(a)
elif b >= a and b >= c:
print(b)
else:
print(c)
maximum(7,11,3)
11
Function arguments can be given a 'default value' that they will take if no other value is specified.
def divide(dividend, divisor=3):
quotient = dividend / divisor
print(dividend, '/', divisor, '=', quotient)
If we call divide
with two arguments, these arguments are set to be the divident and divisor:
divide(12,4)
12 / 4 = 3.0
If we only call divide
with one argument, that is set as the dividend and the divisor takes the default value of 3.
divide(15)
15 / 3 = 5.0
return
can be used in a function to make the function 'give back' a value. This means that you can set a variable equal to the output of a function that returns something, as follows:
def square(x):
x_squared = x * x
return(x_squared)
four_squared = square(4)
print('The return of the function:',four_squared)
The return of the function: 16
You can also return multiple values from a function:
def powers(x):
x_squared = x**2
x_cubed = x**3
x_four = x**4
return(x_squared,x_cubed,x_four)
x2, x3, x4 = powers(4)
print(x2, x3, x4)
16 64 256
Define a function that takes two arguments: a list, and a value. The function should check if the value is present in the list. If the value is present, it should return the index where it is found. Otherwise, it should return nothing.