我是一个新手程序员,我在编写一个基本的猜数字游戏时遇到了一个问题。
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