Quiz #5 for October 13, 2020

Please use your Python system (IDLE or something else) to compute the following. Be prepared to show your work!

  1. If you want to write a program that prints integers from 1 to 19 by twos, which of the following is the most appropriate to use?
    1. A for loop using range(1, 19, 2)
    2. A for loop using range(1, 20, 2)
    3. A for loop using range(1, 20) and a continue statement to prevent the even numbers from printing
    4. A while loop that counts from 1 to 19 by twos, printing the numbers

    Answer: (a) does not include 19, as range() goes up to but not including the upper number. (c) will work, but is clumsy and has an unnecessary if statement. (d) works, but uses a construct (while) intended for an indefinite loop, not a definite one. So (b) is the best answer.

  2. You want to use a while statement to loop, reading input lines until someone types quit. Which of the following is the best way to do this?

    1. A for loop using True as the iterator, and an if statement that compares the input to "quit" and if they match, executes a break
    2. A while loop with input() to read input, and a condition that compares the input to the string "quit"
    3. A while loop with input() to read input, and an if statement that compares the input to "quit" and if they match, executes a break
    4. A while loop with input() to read input, and an if statement that compares the input to "quit" and if they match, executes a continue

    Answer: (a) is obviously wrong, as it doesn’t use a for loop. (d) is wrong, as the continue causes the loop to be executed again, starting at the beginning of the loop. Both (b) and (c) are correct; which on e you should use depends on whether you will use the input in the loop and not just in the conditional. If you will use the input elsewhere in the loop, then (c) is better; if it will only be used in the conditional, (b) would be more appropriate.


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
MHI 289I, Programming for Health Informatics
Version of October 14, 2020 at 11:53PM

You can also obtain a PDF version of this.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh