继续后如何return到循环的特定部分?
How to return to a particular part of a loop after continue?
我正在学习使用 类。我已将异常构建到我定义的方法之一 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),'continue' 再次重新启动整个循环:询问出生月份、日期, 年。我想让它在出错的地方(日期或年份)继续,而不是再次询问用户之前的良好输入以达到这一点。如有任何帮助,我们将不胜感激。
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
然后相同的循环用于日,第三个循环用于年。
我正在学习使用 类。我已将异常构建到我定义的方法之一 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),'continue' 再次重新启动整个循环:询问出生月份、日期, 年。我想让它在出错的地方(日期或年份)继续,而不是再次询问用户之前的良好输入以达到这一点。如有任何帮助,我们将不胜感激。
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
然后相同的循环用于日,第三个循环用于年。