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

Python非区块链简易加密货币程序变量(str/int/global)问题求助

问题根因
  • 初始余额赋值错误:初始balance变量设为-1,不符合你预期的初始1的要求
  • 启动时文件操作逻辑错误:每次启动直接用w模式打开用户文件,w模式会清空文件原有内容,之前存储的余额直接被覆盖,无法持久化
  • 变量类型不匹配:ubalance初始是字符串类型,挖矿时直接和数值类型的balance相加,会触发类型错误
  • 余额更新逻辑错误:挖矿后写入文件的是初始生成的固定log变量,没有更新为最新的余额值,等于写了无效内容
  • 缺失历史余额读取逻辑:程序启动后没有判断用户是否已经注册过,也没有从已有文件中提取历史余额,每次都重新初始化余额,重启自然会重置
修正后代码
import os
import time

user = input("Username:")
filename = f"{user}'s file"

# 先判断用户文件是否存在,存在就读历史余额,不存在初始化余额为1
if os.path.exists(filename):
    with open(filename, 'r', encoding='utf-8') as f:
        content = f.read().strip()
        # 从历史记录提取余额数值
        ubalance = int(content.split(' ')[-2])
else:
    ubalance = 1
    # 写入初始余额记录
    log = f'{user} has a balance of {ubalance} Coinon'
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(log)

os.system("clear")
print(f"Your Current Balance Is {ubalance} Coinon")
print("Mine = 1")
print("Send = 2")
options = input("Selection:")

if options == "1":
    os.system("clear")
    # 这里按照你原来的逻辑循环挖3次,每次等3秒,要挖1次就删掉循环即可
    for x in range(3):
        time.sleep(3)
        # 余额加1
        ubalance += 1
        # 生成最新的余额记录,覆盖写入文件
        new_log = f'{user} has a balance of {ubalance} Coinon'
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(new_log)
        print(f"Your Current Balance Is {ubalance} Coinon")
        print("mine success")
核心修改说明
  • 新增启动时的文件存在判断逻辑,老用户直接读取历史余额,新用户才初始化余额为1
  • 统一用整数类型存储余额,仅在输出、写入文件时做字符串转换,避免类型错误
  • 挖矿后直接用w模式覆盖写入最新余额记录,避免追加写导致的文件冗余,也方便下次启动读取最新余额
  • 修正了余额累加逻辑,每次挖矿余额+1,符合预期功能要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:24:06