@ Ответ Игнасио Васкеса-Абрамса дает формулу.Но если бы их не было, то ваш код как цикл без использования sumYear2
мог бы выглядеть так:
while sumYear >= 10:
sumYear = sum(map(int, str(sumYear)))
Если вам не разрешено использовать sum
(домашнее задание), тогда:
while sumYear >= 10:
s = 0
for d in str(sumYear):
s += int(d)
sumYear = s
По второму вопросу, предполагая Python 3:
while True:
try:
year = int(input("Please enter the year you were born: "))
month = int(input("Please enter the month you were born: "))
day = int(input("Please enter the day you were born: "))
birthday = datetime.date(year, month, day)
except ValueError as e:
print("error: %s" % (e,))
else:
break
Если вам не разрешено использовать try /, кроме случаев:
year = get_int("Please enter the year you were born: ",
datetime.MINYEAR, datetime.MAXYEAR)
month = get_int("Please enter the month you were born: ",
1, 12)
day = get_int("Please enter the day you were born: ",
1, number_of_days_in_month(year, month))
birthday = datetime.date(year, month, day)
Гдеget_int()
:
def get_int(prompt, minvalue, maxvalue):
"""Get an integer from user."""
while True:
s = input(prompt)
if s.strip().isdigit():
v = int(s)
if minvalue <= v <= maxvalue:
return v
print("error: the input is not an integer in range [%d, %d]" % (
minvalue, maxvalue))
И number_of_days_in_month()
:
# number of days in a month disregarding leap years
ndays = [0]*13
ndays[1::2] = [31]*len(ndays[1::2]) # odd months
ndays[::2] = [30]*len(ndays[::2]) # even months
ndays[2] = 28 # February
ndays[8] = 31 # August
# fill other months here ...
def number_of_days_in_month(year, month):
return ndays[month] + (month == 2 and isleap(year))