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

时间:2018-10-24 13:16:35

标签: python

json.Unmarshal(body, data)

我希望data求和为一个数字。 假设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)) 的值为2014,我想将其总和为2 + 0 + 1 + 4 = 7。

3 个答案:

答案 0 :(得分:0)

获取数字的总和是一个古老的经典问题:

def sum_of_digits(number):
    sum = 0
    while number > 0:
      remainder = number % 10
      sum += remainder
      number //= 10
    return sum

答案 1 :(得分:0)

可以将字符串视为列表。因此,如果您将天,月,年的总和制成字符串,然后对其进行循环遍历

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 + year
birthpath = 0
for 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 + year
birthpath = sum(int(digit) for digit in str(total))
print('This is your Birth Path: '+str(birthpath))

答案 2 :(得分:0)

这个简单的班轮就行了!

Birthpath = 2014
sum(int(i) for i in str(Birthpath))