虽然不会停止

时间:2019-07-14 06:10:49

标签: python python-3.x

我从所学课程中获得了锻炼:

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

如果玩家的猜测小于1或大于100,请说“超出界限” 在玩家的第一回合中,如果他们的猜测是 在数字的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

3 个答案:

答案 0 :(得分:1)

问题在于,在match对待匹配中分配给guess_check的操作是局部变量,不会更改“全局” match变量。

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

global match
match = True

我个人更希望从函数中返回匹配值,而不是使用全局变量。

详细了解全局变量here

答案 1 :(得分:1)

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

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()

答案 2 :(得分: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