Functions – How to Reuse and Structure your Program Elements

A function in Python is a way to reuse the same piece of code again and again. It also helps to organize your code better, to make it more readable.

Another way to think of functions in Python is to perform a task. If you need to perform that task, then you basically gives that task a name with the function.

  • Step 1: Inspect the code below and see how it can be re-used.
  • Step 2: Add to the code above, so it also welcomes you.
    • Hint: Call the function with your name.
  • Lesson:
    • Functions are an easy way to re-use code.
    • When the function is called, it executes the following indented lines, and returns where it was called from.
    • A function can take any number of arguments, but should be defined (example welcome(name) takes one argument name, which it can use inside).
  • Step 3: The code below shows how you can re-use other functions.
  • Step 4: Change the code of the function to return the multiplication of all the elements.
    • Hint: The result should be 20 for the first call and 200 for the second.
  • Step 5: The function below changes each entry in a list.
  • Lesson:
    • The built in function len(my_list) returns the number of elements in my_list
    • The for i in range(len(my_list)) iterates with the index i that can be used to access each element my_list[i] in the list to reassign it to a new value.
  • Task 6: Change the function to multiply each element in the list.
  • Exercise:
    • Insert the code in the function all_identical(input_list), which should return True only if all elements in the input_list are equal.
    • You can assume the list is not empty.

Leave a Reply

%d bloggers like this: