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

Python 2.7程序输出结果后如何终止运行?

解决程序终止与循环退出的问题

嘿,我明白你的困惑啦!其实Python程序在所有代码执行完毕后会自动终止,你现在的问题核心是要让最后那个while True循环能正常退出,而不是一直卡着无限循环。咱们一步步来解决:

先优化你现有代码的小问题

你第一个循环里的逻辑有点小瑕疵——你先把输入转成int赋值给HealthScore,但如果用户输入的不是数字,这一步直接就会报错,根本走不到后面的try-except。应该把输入转换的操作放进try块里,这样才能正确捕获非数字输入的错误:

def main():
    pass

Name = raw_input("Enter your name: ")

# 优化后的健康分数输入循环
while True:
    try:
        HealthScore = int(raw_input("Enter your standardised health score: "))
        if 0 <= HealthScore <= 100:
            break
        else:
            print("The number must be in the range 0-100")
    except ValueError:
        print("Please enter a valid number between 0 and 100")

让最后一个循环退出,程序自动终止

对于你没写完的EconomicOutput输入循环,和上面的逻辑一样,当用户输入符合要求时用break跳出循环,之后执行你的计算输出代码,代码跑完程序就自动终止了。比如:

# 经济产出输入循环(假设要求也是0-100)
while True:
    try:
        EconomicOutput = int(raw_input("Enter your standardised economic output: "))
        if 0 <= EconomicOutput <= 100:
            break
        else:
            print("The number must be in the range 0-100")
    except ValueError:
        print("Please enter a valid number between 0 and 100")

# 这里写你的计算和输出逻辑
print(f"Hello {Name}! Your health score is {HealthScore}, economic output is {EconomicOutput}")
# 到这里代码执行完,程序会自动终止

如果需要中途强制终止程序

要是你在某些特定场景下需要直接终止程序(比如用户输入特定指令退出),可以导入sys模块,用sys.exit():

import sys

# 举个例子:如果用户输入'quit'就退出
while True:
    user_input = raw_input("Enter something (or 'quit' to exit): ")
    if user_input.lower() == 'quit':
        sys.exit("Program terminated by user")
    # 其他逻辑...

这样调整后,你的程序就能在完成所有操作后顺利终止啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:33:21