4.5 Practical Exercises
Exercise 1: Writing and Calling a Function
Write a Python function that takes a list of numbers as input and returns their average. Call this function with a list of numbers and print the result.
Exercise 2: Understanding Variable Scope
Examine the code below and predict what it will output. Then run it to check your understanding.
Exercise 3: Importing and Using a Module
Import the math module and use it to calculate the square root of 16.
Exercise 4: Recursive Function
Write a recursive function to calculate the factorial of a number. Call this function with the number 5 and print the result.
Exercise 5: Error Handling
Modify the function from Exercise 1 to handle the case where the input list is empty (and thus the average is undefined). It should raise an exception with an appropriate error message in this case.
These exercises cover the concepts discussed in this chapter. Solving them will help reinforce your understanding of how to define...