Homework Solution

While Loops

Problems to be Submitted (20 points)

  1. (10 points)

    Write a program that allows the user to enter words, continuing until the user first enters a duplicate. Your program should work as showin in the following interaction. (The underlined parts are those parts typed by the user.)

    Start entering words:
    kiwi	
    apple	
    banana	
    apple	
    You already entered apple.
    You listed 3 distinct words.

    Solution:

    print("Start entering words:")
    previous = []
    word = input()
    while word not in previous:
        previous.append(word)
        word = input()
    print("You already entered " + word + ".")
    print("You listed", len(previous), "distinct words.")
    
    (click to see it run live)

  2. (10 points)

    Write a program that answers the following question. Starting with the value x = 1, how many times can x be doubled before reaching one million or more?

    Submit both your source code and the answer you computed for the above question.

    Solution:

    x = 1
    count = 0
    while x < 1000000:
        x *= 2
        count += 1
    
    print(count-1) # number of pushes that are done BEFORE reaching million
    The result is that you can double 19 times while remaining below one million, and that the 20th double pushes you above that threshold.


Last modified: Saturday, 06 October 2018