Python 将数字相加

Python 将数字相加,python,python-2.7,math,Python,Python 2.7,Math,我正在翻阅一本书,我被指示制作一个程序,从用户那里读取一个四位数的数字,然后在四位数相加时返回值 例如:3141:3+1+4+1=9 。 我该如何对数字进行分解和排序?一种方法是将int转换为string并将其拆分,然后使用sum Ex: n = 3141 print(sum([int(i) for i in str(n)])) #list comprehension print(sum(map(int, list(str(n))))) #using map 9 输出: n =

我正在翻阅一本书,我被指示制作一个程序,从用户那里读取一个四位数的数字,然后在四位数相加时返回值

例如:3141:3+1+4+1=9


我该如何对数字进行分解和排序?

一种方法是将int转换为string并将其拆分,然后使用
sum

Ex:

n = 3141
print(sum([int(i) for i in str(n)]))   #list comprehension 
print(sum(map(int, list(str(n)))))     #using map
9
输出:

n = 3141
print(sum([int(i) for i in str(n)]))   #list comprehension 
print(sum(map(int, list(str(n)))))     #using map
9

无需使用
str()
/
int()
转换前后跳跃,也无需在单个数字上迭代:

def sum_digits(number):
    if number < 10:
        return number
    return number % 10 + sum_digits(number // 10)

print(sum_digits(3141))  # 9
def和数字(数字):
如果数字小于10:
返回号码
返回编号%10+和位数(编号//10)
打印(数字总和(3141))#9

也应该快得多。

当用户键入数字时,您可以得到一个
字符串。可以使用
拆分(分隔符)
将此字符串滑入
列表中

例如:

digits = 1234
list_digit = digits.split("")  //I lived blank the separator as there is no character between each value we need. 
print list_digit
它将返回
list_digit=['1','2','3','4']

因此,您只需使用
for
遍历列表中的所有值即可

total = 0
for digit in list_digit:
    print digit
    total = total+int(digit) //Note the convertion from string to int to avoid any error. 
print total

这可能不是最短的,但它会起作用的

到目前为止你做了什么?我投票结束这个问题,因为它是离题的homework@PaoloStefan当前位置家庭作业本身并不会让问题偏离主题,但缺乏努力确实会让问题偏离主题。谢谢!虽然我很抱歉占用了你一些时间,但我只是想出来了,对不起!不客气:)