Friday, December 12, 2014

1.3.8 Activity response: While loops

Here I made a guessing game where you have to guess a number between 1 and 20 inclusive. It tells you if you guessed too high or too low, and even if you guessed a number outside of 1-20.

import random
def goguess():
    maxval = 20
    minval = 1
    target = random.randint(minval, maxval)
    print("I have a number between " + str(minval) + " and " + str(maxval) + ".")
    guess = int(raw_input("Guess: ")) #We put our first guess here because we check
    count = 1                         #the guess at the beginning of the while loop.
    while (not (guess == target)): #the while loop ends when you guess the number.
        if (guess <= maxval and guess >= minval):
            if (guess < target):
                print(str(guess) + " is too low.")
            else:
                print(str(guess) + " is too high.") # Tells if the guess is high or low.
            count += 1 #adds 1  to the count... count.
        else:
            if guess > maxval:    #Remind them if they guess outside the range.
                print(str(guess) + "is higher than " + str(maxval) + ".")
            else:
                print(str(guess) + "is lower than " + str(minval) + ".")
        guess = int(raw_input("Guess: "))
    print("You got it! The number was " + str(target) + ", and you guessed it in " + str(count) + " turns.") #This prints when the 'while' loop ends.

Conclusion question answers:

Q1: If you change between 1 and 20 from the previous program to between 1 and 6000, how many guesses will you need to guarantee that you have the right answer? Explain.

A1: To figure out how many guesses you need, you need find the first power of two above the maximum number. For example, guessing a number in a range 1-7 inclusive would take only three guesses.
2^guesses > max
2^3   = 8       > 7       --3 guesses for a range 1-7
2^5   = 32     > 20     --5 guesses for a range 1-20
2^13 = 8192 > 6000 --13 guesses for a range 1-6000.


Q2: Explain the difference between a while loop and a for loop.

A1: A "while" loop repeats constantly until a condition is met, whereas a "for" loop iterates through a list of values. In some languages like java you could use them interchangeably, but it's generally easier and faster to use whichever one makes more sense for the situation.

1 comment: