In: Computer Science
PYTHON Exercise 5. Guess the number
1. Develop a “Guess the number” game. Write a program that comes up with a random number and the player has to guess it. The program output can be like this: I am thinking of a number between 1 and 20. Take a guess. 10 Your guess is too low. Take a guess. 15 Your guess is too low. Take a guess. 17 Your guess is too high. Take a guess. 16 Good job! You guessed my number in 4 guesses!
2. Complicate it by having random lower and upper bounds. Make sure your lower bound is not higher than you upper bound!
3. Now, instead of user input make the code guess it automatically. Make sure that for the automatic guesses you don’t use the number to guess.
CODE IN PYTHON:
import random
rand = random.randrange(1,21)
guess = input("I am thinking of a number between 1 and 20. take a
guess:")
guess = int(guess)
count = 0
while(True):
count +=1 ;
if(guess==rand):
print("Good job")
break;
elif(guess>rand):
guess = input("Your guess is too high. take a guess:")
guess = int(guess)
else:
guess = input("Your guess is too low. take a guess:")
guess = int(guess)
print("you guessed my number in "+str(count)+" times")
Indentation:
OUTPUT:
CODE IN PYTHON:
import random
rand = random.randrange(1,21)
print("I am thinking of a number between 1 and 20. take a
guess:")
low = 1
high = 20
guess = random.randrange(low,high+1)
count = 0
while(low<=high):
count +=1 ;
print("Your guess is:",guess)
if(guess==rand):
print("Good job")
break;
elif(guess>rand):
high = guess-1
if(low<=high):
print("Your guess is too high. take a guess:")
guess = random.randrange(low,high+1)
else:
low = guess+1
if(low<=high):
print("Your guess is too low. take a guess:")
guess = random.randrange(low,high+1)
print("you guessed my number in "+str(count)+" times")
Indentation:
OUTPUT: