我试图让用户输入出生日期,然后在这些数字中添加单独的整数。此外,如果这些数字的和大于或等于10,则循环重复,并且该过程再次运行该值。到目前为止,我的代码如下
if (sumYear >= 10):
sumYear2=0
for num in str(sumYear):
sumYear2 += int(num)
print(sumYear2)这是可行的,但是我认为它会更好的循环。如果有某种方式,我就不用使用像sumYear2这样的东西了,那就太好了。注意,我不认为我可以使用sum()函数。
谢谢你们的帮助。不过,我有个问题。我不确定为什么当我将月份设置为02,日期设置为30时,没有对此代码进行评估
while True:
year=input("Please enter the year you were born: ")
month=input("Please enter the month you were born: ")
day=input("Please enter the day you were born: ")
if(int(month)==2 and int(day)<=29):
break
elif(int(month)==1 or 3 or 5 or 7 or 8 or 10 or 12 and int(day)<=31 ):
break
elif(int(month)==4 or 6 or 9 or 11 and int(day)<=30):
break
else:
print("Please enter a valid input")发布于 2011-10-23 02:26:15
工作太多了。
singledigitsum = (int(inputvalue) - 1) % 9 + 1请注意,对于小于1的数字,此操作将失败。
发布于 2011-10-23 03:07:00
@Ignacio Vazquez-Abrams's answer提供了该公式。但如果没有,那么不使用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/except,则:
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) Where 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))发布于 2011-10-23 02:28:41
你可以做到的
>>> d=123456
>>> sum(int(c) for c in str(d))
21https://stackoverflow.com/questions/7861671
复制相似问题