继续后如何返回循环的特定部分?
Posted
技术标签:
【中文标题】继续后如何返回循环的特定部分?【英文标题】:How to return to a particular part of a loop after continue? 【发布时间】:2016-02-21 02:25:21 【问题描述】:我正在学习使用类。我已经在我定义的方法之一 setBirthday 中构建了异常。它确保输入适合于真正的生日输出。这部分代码没有按我的意愿工作。
def setBirthday(you):
while True:
#get numeric birth month
try:
m = int(raw_input("What is your birth month?"))
except ValueError:
print "Enter an integer, please try again."
continue
if m <= 0:
print "Enter a number between 1-12, please try again."
continue
elif m >= 13:
print "Enter a number between 1-12, please try again."
continue
#get birth date
try:
d = int(raw_input("What day were you born that month?"))
except ValueError:
print "Enter an integer, please try again."
continue
if d <= 0:
print "Enter a number between 1-31, please try again."
continue
elif d >= 32:
print "Enter a number between 1-31, please try again."
continue
#get birth year
try:
y = int(raw_input("What year were you born?"))
except ValueError:
print "Enter an integer, please try again."
continue
if y <= 0:
print "Enter a number greater than zero, please try again."
continue
else:
break
you.bday = datetime(y, m, d)
age = str(m) + "/" + str(d) + "/" + str(y)
print "Your birthday is " + (age)
当它现在运行时,如果有人在月份 (d) 或出生年份 (y) 输入了不需要的输入,“继续”将再次重新启动整个循环:询问出生月份、日期、年份。我想让它在出错的地方继续(日期或年份),而不是再次向用户询问以前的良好输入以达到这一点。任何帮助将不胜感激。
【问题讨论】:
我会把它分成三个不同的循环,当我得到有效的输入时用break
退出它们。
当我在每次询问后添加“else”“break”时,这个月不会继续。
【参考方案1】:
while True:
#get numeric birth month
try:
m = int(raw_input("What is your birth month?"))
except ValueError:
print "Enter an integer, please try again."
continue
if m <= 0 or m >= 13:
print "Enter a number between 1-12, please try again."
else:
break
然后是一天的相同循环和一年的第三个循环。
【讨论】:
以上是关于继续后如何返回循环的特定部分?的主要内容,如果未能解决你的问题,请参考以下文章