Answer:
import random as ra
#First function
def takenum(guess):
print('Is ' ,guess, ' your number: ')
while True:
num = int(input('\\ Enter 1 if guess is correct \\ Enter 2 if guess is
higher \\ Enter 3 if guess is lower \\ ---Enter Number :'))
try:
if num == 1 or num == 2 or num == 3:
return num
break
else: raise
except:
print('enter a correct parameter')
#Second function
def guessGame():
a=1
b=20
count = 0
guess = ra.randint(a, b)
while count < 6:
num = takenum(guess)
if num == 1:
print('-----correct----')
break
elif num == 2:
count = count + 1
print('')
a = guess + 1
guess = (a + b)//2
elif num == 3:
count = count + 1
print(' ')
b = guess - 1
guess = (a + b)//2
if count == 5:
print('----You cheated------')
break
return
guessGame()
Step-by-step explanation:
This code was written in python 3
Firstly we have to import the random method which will help us generate random numbers.
#Function 1
We define the function and give it one argument. The first function as described in your question takes an int argument 'guess' and asks the user 'Is this your number'. It goes a step further to ask the user if the guess is correct, too low or too high.
it asks the user to enter:
1 if guess is correct
2 if guess is higher
3 if guess is lower
The try and except block is optional but i added it to ensure that the inputs are accurate.
finally, this first function returns an integer num.
#Function 2
firstly, we define the function
a and b are the upper and lower range values
count is our counter which will be used to iterate over the loop.
- we declare a variable guess and assign a random value to it. note that this same variable is the argument for the first function and the first guess and the range used is between 1 and 20.
This program allows for only 5 tries. so WHILE the number of tries is less than 6, it will keep guessing but at the 5th guess if you still don't affirm that the answer is correct, it will tell you that you cheated.
Remember the first function returns an integer num.
The IF loops make use of this num integer gotten from the first function to execute their blocks.
print('------correct-----')
break
' 1 ' here implies that the value is correct from the first function. the IF block in this case prints out that the guess was correct and breaks
count = count + 1
print('')
a = guess + 1
guess = (a + b)//2
'2' here implies that the guess is higher, as a result the lower bound(a) is changed. 1 is added from the guess and assigned as the new lower bound and floor division is performed to get another guess. but this time a calculated guess.
count = count + 1
print(' ')
b = guess - 1
guess = (a + b)//2
'3' here implies that the guess is lower, as a result the upper bound(b) is changed. 1 is subtracted from the guess and assigned as the new upper bound and floor division is performed to get another guess. but this time a calculated guess.
finally, we call the function