1. Q: 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.
2. Q: Describe the difference between a while loop and a for loop.
1. A: 13 times because 2^13 > 6000.
2. A: The difference between a while loob and a for loop is that a while loop loops until a condition changes. A for loop iterates through a variable or some sort of item.
1.3.8 Code File
from __future__ import print_function import random def goguess():
# Initialises variables and sets the random number
tries = 0
randnum = random.randint(1,20)
guess = 0
while guess != randnum:
# Sets guess to the integer of the input and checks its relation to the random number.
guess = int(raw_input('I have a number between 1 and 20 inclusive.\nGuess: '))
if guess > randnum:
print(guess, 'is to high.')
tries += 1
if guess < randnum:
tries += 1
print(guess, 'is to low.')
else: # Once guess == randnum
print('Good job the number was', randnum, 'and it took you', tries, 'tries.')
No comments:
Post a Comment