我创建了一个闰年计算器,但唯一的问题是,一旦打印出它的语句,它就会终止。
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')
发布于 2022-05-09 02:40:20
您希望继续重复相同的操作:
因此,解决方案是在真正的循环中嵌入所有内容
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')
发布于 2022-05-09 02:54:19
请查查我的解决方案。看起来您希望程序在检查输入后继续运行。我添加了更多的选项,以继续或退出程序后,检查过程完成。
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
https://stackoverflow.com/questions/72166443
复制相似问题