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

Python硬币翻转统计程序多次运行计算错误问题排查

硬币翻转统计程序重新运行后计算错误的排查与修复

核心问题定位

你的程序错误根源在于变量赋值顺序完全颠倒:

  • count_flips()函数返回的顺序是 heads_count, tails_count, total_flips(正面数、反面数、总次数)
  • 但主程序里的赋值语句写成了 total_flips, heads_count, tails_count = count_flips(),相当于把正面数赋值给了总次数变量,反面数赋值给了正面数变量,总次数赋值给了反面数变量。

以你给出的错误场景为例:首次运行后文件里有3个H、3个T,count_flips()返回(3, 3, 6),但赋值后:

  • total_flips = 3(实际应该是6)
  • heads_count = 3(这个碰巧对了)
  • tails_count = 6(实际应该是3)

这时候输入T,程序会让total_flips +=1变成4,tails_count +=1变成7,就出现了“tails 7 times out of 4”这种完全矛盾的结果。

次要优化点

写入文件时的"h \n"和"t \n"带有多余空格,虽然line.strip()能处理,但建议改成"h\n"和"t\n",避免不必要的字符处理。

修复后的代码

def count_flips():
    # Open the text file.
    with open("flip_results.txt", "r") as file:
        # Read the file into a list.
        lines = file.readlines()
        # Define the variables starting at zero.
        heads_count = 0
        tails_count = 0
        # Loop through the list, and update the variables based on the number of "h" heads or "t" tails.
        for line in lines:
            if line.strip().lower() == "h":
                heads_count += 1
            elif line.strip().lower() == "t":
                tails_count += 1
    # Define the total number of flips as the sum of heads and tails.
    total_flips = heads_count + tails_count
    # Return the variables for use below in the while loop.
    return heads_count, tails_count, total_flips

# 修正赋值顺序
heads_count, tails_count, total_flips = count_flips()

while True:
    # Get user input and strip it of whitespace.
    result = input("Flip a coin (Enter 'H' for heads or 'T' for tails): ")
    result = result.strip().lower()
    # Check if the user input is "h" or "t".
    if result == "h":
        # If it's heads, print heads, and write "h" to the file.
        print("Heads!")
        with open("flip_results.txt", "a") as file:
            # 去掉多余空格
            file.write("h\n")
        # Update the variables.
        total_flips += 1
        heads_count += 1
        # Calculate the percentage and print it.
        print(f"You have flipped heads {heads_count} times out of {total_flips}.")
        print(f"You have flipped heads {heads_count / total_flips * 100}% of your flips.")

    elif result == "t":
        print("Tails!")
        with open("flip_results.txt", "a") as file:
            # 去掉多余空格
            file.write("t\n")
        # Update the variables.
        total_flips += 1
        tails_count += 1
        # Calculate the percentage and print it.
        print(f"You have flipped tails {tails_count} times out of {total_flips}.")
        print(f"You have flipped heads {heads_count / total_flips * 100}% of your flips.")
    else:
        print("Invalid input. Try again.")
        continue

排查思路总结

  1. 打印初始变量值:在赋值后添加print(heads_count, tails_count, total_flips),对比文件里的实际记录数,就能快速发现变量值和预期不符的问题。
  2. 核对返回与赋值顺序:检查函数返回的变量顺序和接收时的顺序是否完全一致,这是新手常犯的低级错误,但很容易被忽略。
  3. 调试文件读取逻辑:打印lines列表的内容,确认文件读取的每一行是否被正确处理,排除读取错误的可能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 10:45:19