所以我正在尝试编写一个代码,计算机会猜到用户想到的数字。我使用了(x,y)之间的范围,给了x和y 0和10的值。
计算机在这些之间选择一个随机数,而不是询问数字是否正确,如果不是,则询问它是否更高或更低。
这是棘手的部分,或者实际上只是我想要解决它的方式。如果用户说它是一个更高的数字,那么它将x
设置为猜测数,然后循环回到猜测部分,然后再次,如果它更低,y
被设置为猜测
这是我为此编写的代码:
import random
x = 0
y = 10
guessing_loop = "y"
no_guess = 0
while guessing_loop == "y":
guess = random.randint(x - 1,y + 1)
no_guess = no_guess + 1
print("The number I think you thought of is",guess,".")
TF = input("Did you think of that number?")
if TF in {"yes","y","yeah"}:
print("Hell yeah, the number of guesses I had was:",no_guess,".")
elif TF in{"no","nah","nay","n","nope"}:
HL = input("Then was it a higher or a lower number?")
if HL in {"higher","h"}:
x = guess
elif HL in {"lower","l"}:
y = guess
input()
为什么这段代码不起作用?
这段代码根本不符合我的预期,它不会在猜测之间寻找随机数,或者我甚至不确定是什么问题。
答案 0 :(得分:3)
几个问题:
lower_bound
和upper_bound
代替x
和y
。random.randint(x - 1,y + 1)
,您需要random.randint(x + 1,y - 1)