I am new to Python. I have a program that asks the user for an input, and then the program tries to randomly guess what the user inputed, but narrows its search range by asking if it was 'too high' or 'too low'.
How do I make it so that after the user inputs 'too high' or 'too low' it reruns the guessing function?
Also please look at my code for suggestions on improvement. Thanks!
import random
while True:
inp = int(input("type in a number (between 0 and 100) \n> "))
if inp > 0 and inp < 101:
break
else:
print ('sorry try again')
def guessmachine(x):
guesstries = 0
guess = random.randint(0, 100)
print ("my guess was %s" %guess)
if guess != x:
while True:
guesstries += 1
response = input('was my guess too high or too low? Tell the truth \n>')
if response == 'too high':
guess = random.randint(0, guess) #assigning new guess range to narrow down possibilities
return guess
break
guessmachine(inp) #how do I make it rerun guessmachine and guess all over again?
elif response == 'too low':
guess = random.randint(guess, 100) #assigning new guess range to narrow down possibilities
return guess
break
guessmachine(inp) #how do I make it rerun guessmachine and guess all over again?
else:
print ('sorry didnt get that')
else:
print ("Found it! Your number was %s and it took me %s tries" %guess, guesstries)
guessmachine(inp)
updated:
import random
while True:
inp = int(input("type in a number (between 0 and 100) \n> "))
if inp > 0 and inp < 101:
break
else:
print ('sorry try again')
def guessmachine(x, guess, guesstries):
print ("my guess was %s" %guess)
if guess != x:
while True:
response = input('was my guess too high or too low? Tell the truth \n>')
if response == 'too high':
guess = random.randint(0, guess)
guesstries += 1
newguess = guess
guessmachine(inp, newguess,guesstries)
elif response == 'too low':
guess = random.randint(guess, 101)
guesstries += 1
newguess = guess
guessmachine(inp, newguess,guesstries)
else:
print ('sorry didnt get that')
else:
print ("Found it! Your number was %s and it took me %s tries" %guess, guesstries)
guessmachine(inp, random.randint(0, 100), 1)