蟒蛇。 while循环中的变量不更新。

时间:2018-06-21 19:09:18

标签: python

我对编程很陌生,我一直在写一个基本的猜谜游戏时遇到问题。 x是计算机生成的随机数。该程序应该将(previous_guess-x)的绝对值与新猜测值减去x进行比较,并告诉用户他们的新猜测值是更接近还是更远。

但是变量previous_guess没有使用新值更新。 任何帮助将不胜感激。

这是到目前为止的代码:

    ###Guessing Game
import random

n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)

##print(x) ## testing/cheating.
count = 0

while True:
    previous_guess = 0 # Should update with old guess to be compared with new guess
    guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
    count += 1

    print(previous_guess)
    print("Guesses: ", count)

    if guess > n:
        print("Goodbye.")
        break

    elif count < 2 and guess != x: 
        print("Unlucky.")
        previous_guess = guess #####

    elif count >= 2 and guess != x:
        if abs(guess - x) < abs(previous_guess - x):
            previous_guess = guess #####

            print("Getting warmer...")
        else:
            previous_guess = guess #####
            print("Getting colder...")

    elif guess == x:
        print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
        break 

3 个答案:

答案 0 :(得分:9)

您每次循环时都会重新初始化您先前的猜测。这是编程中非常常见的错误,所以不仅是您自己!

将其更改为:

previous_guess = 0
while True:
   #Rest of code follows

这种事情出现时,您应该考虑的事情。

  1. 您的变量在哪里声明?
  2. 您的变量在哪里初始化?
  3. 您的变量在哪里使用?

如果您不熟悉这些条款,那就可以了!看他们!作为程序员,您必须精通谷歌搜索或搜索文档(或在堆栈溢出时询问问题,而您似乎已经发现了)。

学习如何调试对开发有用的东西至关重要的其他事情。

Google“ python调试教程”,找到一个有意义的内容(确保您可以真正跟随该教程),然后就不用了。

答案 1 :(得分:8)

每次循环再次开始时,您都将previous_guess重置为0,因此丢弃了实际的先前猜测。相反,您想要:

previous_guess = 0
while True:
    guess = ....

答案 2 :(得分:2)

您需要在previous guess循环之前初始化while。否则它将一次又一次地初始化。 您已经在多个地方更新了previous guess。您可以使其更简单:

import random

n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)

##print(x) ## testing/cheating.
count = 0
previous_guess = 0  # Should update with old guess to be compared with new guess
while True:
    guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
    count += 1

    print(previous_guess)
    print("Guesses: ", count)

    if guess > n:
        print("Goodbye.")
        break
    elif count < 2 and guess != x:
        print("Unlucky.")
    elif count >= 2 and guess != x:
        if abs(guess - x) < abs(previous_guess - x):
            print("Getting warmer...")
        else:
            print("Getting colder...")
    elif guess == x:
        print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
        break
    previous_guess = guess  #####