Verifying Inputs
Objectives
- Learn to think about what kinds of values a function should accept
- Write code that verifies inputs and rejects improper arguments
Background
So far in our programming we have been assuming that the user will enter the input we expect. This assumption often does not hold. One of the most important parts of interactive programming is ensuring that the user enters the input the program expects. This problem asks you to implement several short programs to verify properties of a user’s input. After completing this assignment, you should use these input verification techniques in all future interactive programs you write.
For each of the problems below, the loop should repeat if the input is incorrect.
Problem 1: first_num_larger()
Asks the user to enter two numbers where the first is larger than the second, and prints either an acceptance message and ends, or an error message and reprompts the user to enter two numbers.
Problem 2: sum_to_42()
Asks the user to enter 5 numbers whose sum is 42. If the numbers sum to 42, the program prints an acceptance message that summarizes the user’s entry and ends; otherwise the program should reprompt the user to enter 5 numbers that sum to 42.
Problem 3: first_n_fibs(n)
Asks the user to enter the first n numbers of the fibbonacci sequence. If the user enters an incorrect value at any point, the program should immediately prompt the user to re-enter that number (rather than waiting until the end to tell the user they have made a mistake). When prompting, the program should summarize the user’s progress so far.
Below are examples of these three functions in action. Have your functions print the same information that these examples show. In fact, you can save time by copying-and-pasting some of these strings if you like (other parts of the output will have to be generated by loops).
Note that your program should print the same information that the demos above print. For some of these problems, you will probably need to use a loop to do this printing (because you have to print the plus signs between the numbers, for example). As you have seen print automatically prints a newline after its input. However, you can suppress this behavior (to make multiple calls to print all print on the same line) by including a the parameter end="" in your call to print, for example:
will print