You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python猜水果游戏:guesses变量重启后无法保留值的问题求助

猜水果游戏的分数持久化问题

我写了一个猜水果的Python游戏,猜对水果时guesses变量会加1,但输入“yes”重启游戏后,该变量会重置为0。我尝试通过文件写入将其保存到外部文件,但并未成功。

初始代码

import random


x = ["banana", "pineapple", "mango"]

def restart():
    guesses
    al = ['yes', 'no']
    r = input("Do you want to play again (yes/no with lower case letters): ")
    if r == "yes":
      game()
    elif r == "no":
      exit()
    else:
      print("Sorry i didn't get that.")
      restart()
    
 

def game():
 gf = open('guesses.txt', 'w')
 global guesses
 guesses = 0
 y = input("Guess the fruit: ")
 z = random.choice(x)


 if y == z:
    
    guesses += 1
    gf.write(str(guesses))
    print("Your answer was correct, you now have:", guesses)
    restart()
 else:
     guesses = guesses 
     print("Your answer was wrong, you now have:", guesses)
     restart()


game()

相关信息

  • 期望:变量能保存到外部文件,在程序重新执行后依然保留
  • 尝试:函数重新执行后保存变量
  • 结果:变量未成功保存

编辑:问题已解决

修正后的代码如下:

import random

guesses = 0
x = ["banana", "pineapple", "mango"]

def restart():
    guesses
    al = ['yes', 'no']
    r = input("Do you want to play again (yes/no with lower case letters): ")
    if r == "yes":
      game()
    elif r == "no":
      exit()
    else:
      print("Sorry i didn't get that.")
      restart()
    
 

def game():
 gf = open('guesses.txt', 'w')
 y = input("Guess the fruit: ")
 z = random.choice(x)
 global guesses

 if y == z:
    
    guesses += 1
    gf.write(str(guesses))
    print("Your answer was correct, you now have:", guesses)
    restart()
 else:
     if guesses > 0: guesses -= 1
     print("Your answer was wrong, you now have:", guesses)
     if guesses == 0:
      restart()
 gf.close()



game()

内容的提问来源于stack exchange,提问作者ItsMeData

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 06:05:15