0

我在学习的课程中有一个练习:

编写一个程序,从 1 到 100 中选择一个随机整数,让玩家猜数字。规则是:

如果玩家的猜测小于 1 或大于 100,则说“OUT OF BOUNDS” 在玩家的第一轮,如果他们的猜测在数字的 10 以内,则返回“WARM!” 距离号码超过 10,返回“COLD!” 在所有后续回合中,如果猜测比前一个猜测更接近数字,则返回“WARMER!” 比之前的猜测离数字更远,返回“COLDER!” 当玩家的猜测等于数字时,告诉他们他们猜对了以及猜了多少次!

由于某种原因,即使猜对了,它仍然会要求我输入一个新的数字。你能帮我修一下吗?

from random import randint

# picks random integer
raffle = randint(1,100)

# entering first guess
guess = int(input("Guess the random number: "))

# checking first guess
if guess < 1 or guess > 100:
    print("OUT OF BONDS")
else:
    if guess == raffle : 
        print("Correct! You figured the number after the first try!")
    else if guess > raffle:
        if guess-raffle < 11:
            print("WARM!")
        else:
            print("COLD!")
    else:
        if raffle-guess < 11:
            print("WARM!")
        else:
            print("COLD!")

guess_count = 1
match = False

def guess_check():
    next_guess = int(input("Guess the random number again: "))
    if next_guess < 1 or guess > 100:
        print("OUT OF BONDS")
    else:
        if next_guess == raffle : 
            print("Correct! You figured the number!")
            match = True
        elif next_guess > raffle:
            if next_guess-raffle < 11:
                print("WARMER!")
            else:
                print("COLDER!")
        else:
            if raffle-next_guess < 11:
                print("WARMER!")
            else:
                print("COLDER!")

while match != True:
    guess_check()

print(f"The random number is: {raffle}")
```python
4

3 回答 3

1

问题是对match内部guess_check处理匹配的赋值是一个局部变量,不会改变“全局”match变量。

guess_check一种解决方案是在更改匹配值之前添加以下内容-

global match
match = True

就个人而言,我宁愿从函数中返回匹配值,而不是使用全局变量。

在此处查看有关全局变量的更多信息

于 2019-07-14T06:20:06.980 回答
1

只需让您的函数guess_check()返回一个布尔值 True 或 False,而不是使用全局变量match。然后,当您guess_check()在 while 循环中调用时,您需要将 match 重新分配给guess_check(). IE

def guess_check():
    next_guess = int(input("Guess the random number again: "))
    if next_guess < 1 or guess > 100:
        print("OUT OF BONDS")
    else:
        if next_guess == raffle : 
            print("Correct! You figured the number!")
            return True
        elif next_guess > raffle:
            if next_guess-raffle < 11:
                print("WARMER!")
            else:
                print("COLDER!")
        else:
            if raffle-next_guess < 11:
                print("WARMER!")
            else:
                print("COLDER!")
    return False

while match != True:
    match = guess_check()
于 2019-07-14T06:29:36.523 回答
0

正如@TomRon 所提到的,您需要添加这些行,并且在最后一个打印语句中您需要修改如下:

print("The random number is: {raffle}".format(raffle=raffle))

因此,新代码可能如下所示:

        if next_guess == raffle:
            print("Correct! You figured the number!")
            global match
            match = True
于 2019-07-14T06:33:16.017 回答