Basic functions
A function is a reusable piece of code that is only run when it is called. Functions can have inputs, and they usually return an output. For example, using a Python shell, you can define the following function that takes two inputs, base
and height
, and returns their product as the area:
def area(base, height):
return base*height
area(2, 3)
The output is as follows:
6
Exercise 43 – defining and calling a function in the shell
In this exercise, you create a function that will return the second element of a list if it exists. Proceed as follows:
- In a Python shell, enter the function definition. Note that the tab spacing needs to match the following output:
def get_second_element(mylist):
if len(mylist) > 1:
return mylist[1]
else:
return 'List was too small'
- Try...