#setBirthday sets their Birthday to a date
def setBirthday(self):
while True:
try:
day = int(raw_input('Please enter the date of the month (1-31) you were born on here ->'))
if day <= 0 or day >= 32:
print "better try again..."
except ValueError:
continue
else:
break
month = int(raw_input('Please enter the month of the year (1-12) you were born on here ->'))
if month <= 0 or day >= 13:
print "better try again..."
except ValueError:
continue
else:
break
year = int(raw_input('Please enter the year you were born (19xx or 20xx) here ->'))
self.birthday = datetime(year, month, day)
print str(varPerson.getName()) + " you were born on " + str(month) + "/" + str(day) + "/" + str(year)
缩进错误位于varPerson最后3行之上。我已经尝试过尝试让这个场景与异常一起工作,以便能够拥有一个平滑的运行脚本,如果值不合适,可以允许额外的尝试。建议?我一直在使用此链接寻求帮助:
答案 0 :(得分:5)
不要试图修复上面的内容,而是要仔细查看代码并弄清楚你想要做什么。然后,询问如何在StackOverflow或另一个StackExchange网站上最好地实现这个关注客观的大问题,展示你到目前为止所尝试过的内容。
答案 1 :(得分:1)
为什么要在循环中定义setBirthday?
while True:
try:
def setBirthday(self):
while True:
try:
答案 2 :(得分:1)
如果您真的想要处理任何异常,请尝试以下代码:
import datetime
from datetime import datetime
class Person(object):
def __init__(self, name):
self.name = name
self.birthday = None
#getName returns the name of the person
def getName(self):
return self.name
#setBirthday sets their Birthday to a date
while True:
try:
def setBirthday(self):
while True:
try:
day = int(raw_input('Please enter the date of the month (1-31) you were born on here ->'))
month = int(raw_input('Please enter the month of the year (1-12) you were born on here ->'))
year = int(raw_input('Please enter the year you were born (19xx or 20xx) here ->'))
self.birthday = datetime(year, month, day)
print str(varPerson.getName()) + " you were born on " + str(month) + "/" + str(day) + "/" + str(year)
except ValueError:
print "better try again...return to the start of the loop"
continue
else:
break
#if day <= 0 or day >= 32:
#print "Please enter a number between 1 and 31. Try again."
#getAge returns how many days old the individual is
def getAge(self):
dateNow = datetime.now()
dateBirth = self.birthday
timedelta = dateNow - dateBirth
print str(varPerson.getName()) + " you have been living on Earth for " + str(timedelta)
#current date - birthdate to get specific days, timedelta
except:
pass
varPerson = Person(raw_input('Please enter your name here ->'))
varPerson.setBirthday()
varPerson.getAge()
就个人而言,True虽然不好用......