Thanks to Dr. Alan McLeod for the content of this lab.

This lab is designed to give you more practice building conditionals, using boolean expressions and working with functions. Don't forget that you can test boolean expressions using just the Python prompt. You can even test a conditional here, although nesting is probably more work than it is worth at the prompt.

Full solutions are provided for most exercises, but as always, you should try the exercise first before looking at the supplied code.

Exercise 1

This is an altered version of a question from an old CISC 101 midterm. Examine the code in the program Exercise1.py and try to figure out what the output will be for user supplied values of -10, 2000, 50, 61, 900, and 850 just by examining the code. Run the program to check your answers.

Exercise 2

Examine the code for the program GradeCodes.py. It contains a single function main() with a chained if-elif-else structure. Re-write this code to use a nested if structure instead. Here is the sample solution.

Now review the code for the program SortThree.py. It contains a single function main() with a nested if structure. Re-write this code to use a chained if-elif-else structure instead. In addition, create a new function getIntegerFromUser(message) which asks the user for input with the string message, converts the input into an integer and returns the integer. Re-write the first part of main() to use this function. Here is the sample solution.

Compare both versions of both programs to determine which is more efficient. As a measure of efficiency count the maximum number of comparisons made in both versions. Which version did you find easier to write or to understand?

Exercise 3

The two roots of the quadratic equation ax2 + bx +c = 0 are given by the formula:

Of course, if a is zero, the root is simply:

Write a program that obtains the values of a, b and c from the user and then prints out the root or roots of the equation to two decimal places to the screen. You will need to determine:

Consider using a function to get integer input from the user as in the second part of Exercise 2. Here is a solution to this problem.

Exercise 4

In Exercises 5.1 and 6 of the Week 3 lab you wrote a program to convert inches to cm. Add code to your main() function to test the user's input for the distance in inches - it can not be a negative number. Alert the user and do not perform the calculation if this is the case.

More Exercises

You should be able to do any of the Programming Exercises at the end of Chapter 4. While they are not as interesting as the above exercises(!), it might be worth picking one or two that emphasize the chained if structure (#1, 4, 5 or 6).

Here is a sample solution to exercise 5, which is to determine the charge for a $99 package given a set of quantity discounts:


< 10                  no discount

between 10 and 19     20%

between 20 and 49     30%

between 50 and 99     40%

>= 100                50%