如何在函数中重新分配变量?

How can I reassign a variable in a function?

我正在尝试让代码猜测用户心中的数字。该代码应该取一个范围的平均值,并且范围应该随着它的进展而变短。我遇到的麻烦是一旦用户输入数字小于猜测的数字就重新分配范围。在我下面的代码中,在 运行 函数 less() 之后,我希望 high 等于 new_high,这样如果用户再次输入 [less],函数就可以循环。任何帮助将不胜感激。

print("Guess a number between 1 and 100")
low = 1
high = str(100)
new_high = 1
guess = int(0)
question = "Is your number [less] than, [more] than, or [equal] to", high, "?"

def less():
    new_high = (int(high) + int(low)) / 2
    print(float(new_high))
    new_high = int(new_high)
    return high == new_high

while guess <= 7:
    number = input("Is your number [less] than, [more] than, or [equal] to "+high+"? ")
    if number == "less":
        guess = guess + 1
        less()
        print(high)
    elif number == "equal":
        print("It took", guess, "guesses to guess the number.")
        break

return high == new_high

您正在 return 比较,它正在检查 high 是否等于 new_high 和 return 布尔值。

我之前的回答是错误的。

high = new_high
return high

如果你想改变high的值,否则你可以return new_high

您当前从函数 less 返回比较 high 和 new_high 的布尔结果,实际上您并没有将该值赋给任何东西。

下面的代码应该可以解决这个问题。

print("Guess a number between 1 and 100")

low = 1
high = str(100)
new_high = 1
guess = int(0)
question = "Is your number [less] than, [more] than, or [equal] to", high, "?"

def less():
    new_high = (int(high) + int(low)) / 2
    print(float(new_high))
    new_high = int(new_high)
    return new_high

while guess <= 7:
    number = input(f"Is your number [less] than, [more] than, or [equal] to {high}? ")
    if number == "less":
        guess = guess + 1
        high = less()
        print(high)
    elif number == "equal":
        print("It took", guess, "guesses to guess the number.")
        break