我已经开始了一个python初学者项目,在这个项目中,计算机通过输入用户的数字来猜测用户的号码,输入它是高于还是低于x。然而,我已经管理了第一部分,但我的程序停止,并没有继续。我的猜测是,我需要在代码中包含一个循环来重复nextguess(),但是我不知道在哪里。
这是我的密码:
maxnum = 1000
min = 1
guess = 500
print("1 = Higher 2 = Lower 3 = Correct")
print("Pick a number dont tell me what it is!")
print("The highest number you can pick is:",maxnum)
print("The lowest number you can pick is:",min)
print("Is it higher or lower than:",guess)
maxnum = maxnum +1;
choice = input()
choiceprop = int(choice)
def nextguess():
guess = (maxnum + min) / 2
print("Is it lower or higher than:", guess)
if choiceprop == 1:
min = guess
nextguess()
maxnum = maxnum +1;
if choiceprop == 2:
maxnum = guess
nextguess()
maxnum = maxnum +1;
if choiceprop == 3:
print("nice!");发布于 2020-09-01 12:17:31
看起来,您试图使用二进制搜索将用户的号码降到零,您需要注意数字是如何四舍五入的,以及如何根据用户的输入移动边界。
至于将其保持在第一个输入之外,您将需要将接受用户输入并在within循环中进行下一个猜测的部分放在一个while循环中,确保在循环体中有一个代码停止条件或逻辑,以防止它无限循环。
下面是一个如何做到这一点的例子:
import math
def main():
min = 0
max = 1000
print("Pick a number dont tell me what it is!")
print("The highest number you can pick is:", max)
print("The lowest number you can pick is:", min)
while max >= min:
guess = math.ceil((max + min) / 2)
print("Is it higher or lower than: ", guess)
print('1. Higher')
print('2. Lower')
print('3. Correct')
choiceprop = int(input('Option: '))
if choiceprop == 1:
min = guess + 1 # guess can be excluded safely
elif choiceprop == 2:
max = guess - 1
else:
print('nice')
break
main()https://stackoverflow.com/questions/63686230
复制相似问题