Week 6

Solutions to Functions and Imports

Exercise 1.1 - Maximal Entertainment

We create a function to print the maximum value in a given list.

week5_solutions_ex1_1.py
# define function to print out the max value in the list 
def print_max_in_list(a_list):
    # initialise the current_best to be the first item
    current_best = a_list[0]
    
    for item in a_list:
        # update the current best if we see a bigger value
        if item > current_best:
            current_best = item
            
    print("Max Value:" + str(current_best))
    
# test the function with the following
# expect '376' to be printed
example_list = [4, 9, 376, 12, 234, 124, 94, 3]
print_max_in_list(example_list)

Extension 1.1 - Returning max value

Here we return the max value instead, and then print it.

Exercise 1.2 - Sum thing to do

Here we print the sum of all the values in a list

Extension 1.2 - Returning Average

Now we average the values in the list and return the result

Exercise 1.3 - Developing a range of skills

Here we define a function to mimic the range function - which returns a list of integers from the minimum to the max - 1.

Extension 1.3.1 - Default arguments

Add default arguments to our range function, such that if min is not given then the function counts from 0 - We need to alter the function definition and modify our max and min values

Extension 1.3.2 - Recursive Range function

Here we implement the range function using recursion - the function must call itself, and have a terminating condition.

Exercise 2 - Import-ant Syntax

Here we rename some imports and run the 'scary block of awful code'

Last updated

Was this helpful?