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

Python硬币翻转程序:实现重复翻转功能的问题求助

硬币翻转程序重复执行问题解决方法

问题原因

你使用open("Coinflip.py")的方式完全错误——这个函数仅用于打开文件获取读写句柄,并不会执行脚本内的代码,所以选择再次翻转时没有任何效果。

解决方案1:使用循环(推荐)

这是最简洁高效的实现方式,把硬币翻转逻辑放到while循环中,用户选择退出时才终止程序:

import random 
import time  

while True:
    # 执行硬币翻转逻辑
    flip = random.randint(1, 2)  
    if flip == 1:     
        print("The coin landed heads")  
    else:     
        print("The coin landed tails")   
    
    print('\n')  
    time.sleep(1)  
    
    # 获取用户选择并处理输入
    try:
        choice = int(input("Type 1 to exit or 2 to flip again and press enter "))
        if choice == 1:     
            break  # 退出循环,结束程序
        elif choice != 2:
            print("Invalid input, please enter 1 or 2.")
    except ValueError:
        print("Please enter a valid number.")

input()

解决方案2:重新运行脚本(不推荐)

如果非要通过重新执行脚本的方式实现,可以使用subprocess模块调用Python解释器运行脚本,同时终止当前进程:

import random 
import time  
import subprocess
import sys

flip = random.randint(1, 2)  
if flip == 1:     
    print("The coin landed heads")  
if flip == 2:     
    print("The coin landed tails")   
print('') 
print("")  
time.sleep(1)  
choice = int(input("Type 1 to exit or 2 to flip again and press enter "))  
if choice == 1:     
    sys.exit()  
elif choice == 2:     
    # 重新运行当前脚本
    subprocess.run([sys.executable, __file__])
    sys.exit()  # 终止当前进程

input()

注意:第二种方式会启动新进程,效率远低于循环方案,且脚本路径变化时可能出错,优先选择第一种循环实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:16:04