首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何防止我的程序终止?

如何防止我的程序终止?
EN

Stack Overflow用户
提问于 2022-05-09 02:31:25
回答 2查看 33关注 0票数 -1

我创建了一个闰年计算器,但唯一的问题是,一旦打印出它的语句,它就会终止。

代码语言:javascript
运行
复制
year = int(input("Which year do you want to check? "))
leap_year_check = False
already_a_leap_year = False
if year / 4 == int(year / 4):
    if year / 100 != int(year / 100):
        already_a_leap_year = True
    elif year / 100 == int(year / 100):
        leap_year_check = True

if year / 400 == int(year / 400) and leap_year_check and already_a_leap_year == False:
    print("Leap year")
elif already_a_leap_year == True:
    print('Leap year')
else:
    print('Not leap year')
EN

回答 2

Stack Overflow用户

发布于 2022-05-09 02:40:20

您希望继续重复相同的操作:

因此,解决方案是在真正的循环中嵌入所有内容

代码语言:javascript
运行
复制
while True:
    year = int(input("Which year do you want to check? "))
    leap_year_check = False
    already_a_leap_year = False
    if year / 4 == int(year / 4):
        if year / 100 != int(year / 100):
            already_a_leap_year = True
        elif year / 100 == int(year / 100):
            leap_year_check = True

    if year / 400 == int(year / 400) and leap_year_check and already_a_leap_year == False:
        print("Leap year")
    elif already_a_leap_year == True:
        print('Leap year')
    else:
        print('Not leap year')
票数 0
EN

Stack Overflow用户

发布于 2022-05-09 02:54:19

请查查我的解决方案。看起来您希望程序在检查输入后继续运行。我添加了更多的选项,以继续或退出程序后,检查过程完成。

代码语言:javascript
运行
复制
terminate_program = False
exit_program_map = {"Y": True, "N": False}

while not terminate_program:
    year = int(input("Which year do you want to check? "))
    leap_year_check = False
    already_a_leap_year = False
    if year / 4 == int(year / 4):
        if year / 100 != int(year / 100):
            already_a_leap_year = True
        elif year / 100 == int(year / 100):
            leap_year_check = True

    if year / 400 == int(year / 400) and leap_year_check and already_a_leap_year == False:
        print("Leap year")
    elif already_a_leap_year == True:
        print('Leap year')
    else:
        print('Not leap year')


    is_exit_program = str(input("Do you want to continue program? [Y/N] ")).upper()
    if is_exit_program in exit_program_map.keys():
        terminate_program = exit_program_map[is_exit_program]
    else:
        print("Not valid option. Shutdown program")
        terminate_program = True

    if terminate_program is True:
        print("Shutdown program")
        break

示例

代码语言:javascript
运行
复制
Which year do you want to check? 2022
Not leap year
Do you want to continue program? [Y/N] N
Which year do you want to check? 2018
Not leap year
Do you want to continue program? [Y/N] n
Which year do you want to check? 2015
Not leap year
Do you want to continue program? [Y/N] Y
Shutdown program
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72166443

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档