我对Python还不熟悉。我有一个程序,要求用户输入,然后该程序试图随机猜测用户输入的内容,但通过询问“过高”或“过低”来缩小搜索范围。你知道吗
如何使它在用户输入“过高”或“过低”后重新运行猜测功能?你知道吗
另外,请看我的代码的改进建议。谢谢!你知道吗
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)
更新时间:
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)
一个简单的方法是让你的猜测机器返回数字是高还是低(或相等),并将其放入while循环。在一些简单的更改中,它看起来像:
经过一些改进和修正,这里是最后的工作:
编辑:我现在使用一个最大值和一个最小值,这样每次猜测时,我都会缩小随机间隔:
测试用例I(随机,5次尝试):
测试用例II(随机,6次尝试):
相关问题 更多 >
编程相关推荐