首页 > 解决方案 > 满足条件时如何停止循环?

问题描述

我是尝试使用 python 进行编码的新手。在编写一个简单的程序来计算年龄时,我遇到了一个错误,无论我多么努力,我似乎​​都无法修复。代码粘贴在下面。该程序会在我输入未来的一年时运行,但是当使用已经过去的一年时,代码会再次循环询问年份是否正确。任何帮助表示赞赏。

from datetime import date

current_year = (date.today().year)
print('What is your age?') 
myAge = input()
print('future_year?')
your_age_in_a_future_year= input()
future_age= int(myAge)+ (int(your_age_in_a_future_year)) - int(current_year)

def process ():
    if future_age > 0:
        print(future_age)
    else:
        print('do you really want to go back in time?, enter "yes" or "no"')
    answer = input()
    if answer =='yes':
        print (future_age)
    if answer == 'no':
        print ('cya')
    while answer != 'yes' or 'no':
        print ('enter correct response')
        process ()
        
process()

标签: pythonloops

解决方案


尝试

...
   if future_age > 0:

        print(future_age)
        return

    else:

        print('do you really want to go back in time?, enter "yes" or "no"')
...

推荐阅读