#!/usr/bin/env python # coding: utf-8 # # Programming with Python # #### Stefan Güttel, [guettel.com](http://guettel.com) # # ## Exercises: Control flow # The usage of `break` and `continue` can always be avoided with more or less effort (often with at least some loss of readability of the code). However, try to use them where viable, as these are very useful constructs. Most of the following problems can benefit from the usage of these statements. # # As always, write the programs that test your functions. From now on, if a function raises an exception, the program must catch it and deal with it in a meaningful fashion (usually print an appropriate descriptive message). # **Problem 1.** Write a function `print_first_prime(L)` that **prints** the first prime number in the list `L`. # # If there are no primes in the list, the function prints an appropriate descriptive message. # **Problem 2.** Write a function `first_prime(L)` that **returns** the first prime number in the list `L`. # # If there are no primes in the list, the function raises an appropriate exception. # **Problem 3.** Write a function `first_plus_last_prime(L)` that returns the sum of the first and the last prime number in the list `L`. # # If there are no primes in the list, the function returns zero. If there is only one, the function returns its double value (because it is at the same time the first and the last one in the list). # **Problem 4.** (Problem 1 from the "Functions" exercises) Write a function `max_digit(n, d, r)` that works like `digit_sum` from the "Functions" lectures but, instead of returning the sum of the digits of `n`, returns the maximum digit of `n` that gives the reminder `r` when divided by `d`. Assign the appropriate default values for any of the parameters for which it makes sense to do so. # # Notice that this maximum is undefined for some numbers. If this happens, raise an appropriate exception. # **Problem 5.** (Problem 3 from the "Functions" lab class) Write a function `get_digit(n, left, right)`. The function # * returns `d`-th digit of `n` from the left if the function was called as `get_digit(n, left=d)`, # If the required digit doesn't exist, the function must raise a `ValueError` exception. # * returns `d`-th digit of `n` from the right if the function was called as `get_digit(n, right=d)`, or # if the required digit doesn't exist, the function must return 0. # * raises a custom exception (so, make your own instead of using `ValueError` or another predefined one) otherwise, i.e., for `get_digit(n)` and `get_digit(n, left=d1, right=d2)`.