Python 当满足条件时,如何停止循环?
我是一个完全的代码新手,尝试用python编写代码。在编写一个简单的程序来计算年龄时,我遇到了一个错误,无论我怎么努力,似乎都无法修复。代码粘贴在下面。该程序在我输入未来一年的时间内运行,但是当使用已过去的一年时,代码会再次循环询问该年是否正确。感谢您的帮助Python 当满足条件时,如何停止循环?,python,loops,Python,Loops,我是一个完全的代码新手,尝试用python编写代码。在编写一个简单的程序来计算年龄时,我遇到了一个错误,无论我怎么努力,似乎都无法修复。代码粘贴在下面。该程序在我输入未来一年的时间内运行,但是当使用已过去的一年时,代码会再次循环询问该年是否正确。感谢您的帮助 from datetime import date current_year = (date.today().year) print('What is your age?') myAge = input() print('future_
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()
试一试
在这种情况下,您的函数只需要包含一个带有适当条件的
while
循环,然后就不需要从中中断,也不需要执行递归调用或任何操作
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 = None
while answer not in ('yes', 'no'):
answer = input()
if answer == 'yes':
print(future_age)
elif answer == 'no':
print('cya')
您是否花了几天时间阅读???欢迎来到Stack Overflow。这段代码是你自己写的吗?或者你想让我们从其他人那里解释代码?不管怎样,这个问题在这里都不是主题。您可能希望将代码分解成更小的部分,临时打印变量等,以了解发生了什么。“如何停止循环?”这个问题可以在文档中找到,并且可能已经在这里得到了回答。请阅读。谢谢你回来,你可能已经被我糟糕的问题结构甩了,但是,另一个答案似乎已经解决了这个问题。
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 = None
while answer not in ('yes', 'no'):
answer = input()
if answer == 'yes':
print(future_age)
elif answer == 'no':
print('cya')