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 and returns the sum:
def add_up(x, y): return x + y add_up(1, 3)
You should get the following output:
4
Exercise 42: Defining and Calling the Function in Shell
In this exercise, you create a function that will return the second element of a list if it exists:
- 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'
Here you are calling
print
logs the parsed message to the standard output...