繁体   English   中英

如何防止我的程序终止?

[英]How do I prevent my program from terminating?

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

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')

你想继续重复相同的操作:

所以解决方案是将所有内容嵌入while True循环

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')

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

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

例子

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM