猿问

将一个数字相加得到一个数字

print ('Welcome to BirthPath Calculator')


Day = input('Input you day of Birth (1-31): ')

Month = input('Input your month of birth (1-12): ')

Year = input ('Input your year of birth: ')


Day = int(Day)

Month = int(Month)

Year = int(Year)


Birthpath = Day + Month + Year

sum(Birthpath)


print ('This is your Birth Path: '+str(Birthpath))

我希望Birthpath总和为一个数字。让我们假设 的值为Birthpath2014,我想把它加起来为 2+0+1+4=7。


眼眸繁星
浏览 193回答 3
3回答

缥缈止盈

可以将字符串视为列表。因此,如果您将天+月+年的总数变成一个字符串,然后循环遍历它就可以了print('Welcome to BirthPath Calculator')day = int(input('Input you day of Birth (1-31): '))month = int(input('Input your month of birth (1-12): '))year = int(input('Input your year of birth: '))total = day + month + yearbirthpath = 0for digit in str(total):    birthpath += int(digit)print('This is your Birth Path: ' + str(birthpath))您还可以使用列表理解来缩短它的时间。print('Welcome to BirthPath Calculator')day = int(input('Input you day of Birth (1-31): '))month = int(input('Input your month of birth (1-12): '))year = int(input('Input your year of birth: '))total = day + month + yearbirthpath = sum(int(digit) for digit in str(total))print('This is your Birth Path: '+str(birthpath))

杨魅力

这个简单的一个衬垫会起作用!Birthpath = 2014sum(int(i) for i in str(Birthpath))

米琪卡哇伊

得到一个数字的数字和是一个古老的经典问题:def sum_of_digits(number):    sum = 0    while number > 0:      remainder = number % 10      sum += remainder      number //= 10    return sum
随时随地看视频慕课网APP

相关分类

Python
我要回答