[英]sum of all digits in the number by python
我正在尝试编写一个 python 程序来计算数字的数字总和。 请逐行解释,因为我是新手。
我在网上尖叫,发现了这样的东西:-
sum = 0
while (n != 0):
sum = sum + (n % 10)
n = n//10
我不明白这两行的用途请解释一下
sum = sum + (n % 10)
n = n//10
如果你们知道任何其他快速轻松地解决它的方法,请建议我? 谢谢你
# Extract the last digit of the number
(n % 10)
当 n 除以 10 时,使用取模运算符 ( %
) 求余数。(例如,如果n
为 123,则n % 10
将为 3)
# Add it to the sum
sum = sum + (n % 10)
这只是将它添加到sum
变量。
# Remove the last digit from the number
n //= 10
使用底除法运算符 ( //
) 将n
除以 10,并将结果分配回n
。 例如,如果n
是 123,那么n // 10
就是 12。
上一篇帖子详细解释了每个原始代码步骤。 就是计算数字和。 (让它更快)
或者,您可以单行执行此操作:
说明:将数字转换为字符串然后循环并对int(x)求和
注意- 因为总和是 Python内置的- 尽量避免使用它作为变量名。
n = 123
digit_sum = sum(int(x) for x in str(n))
# 6
所以基本上 while 循环运行直到 n 变为 0 让我们举一个例子给定n=2438
最初总和是0
检查是n==0
否...进入while循环
`sum = sum + (n % 10)` -> sum=0+8 as 2438%10=8 which is remainder..!
`n = n//10` -> n=243 after division as you can see the last digit is removed ..!
检查是n==0
否..进入循环
`sum = sum + (n % 10)` -> sum=8+3 as 243%10=3 which is remainder..!
`n = n//10` -> n=24 after division as you can see the last digit is removed ..!
如您所见,上面两个步骤。
sum=11+4
n=2
sum=15+2
n=0
检查是 n==0 是的 while 循环中断..!
在获得结果时打印总和
作为初学者,您应该想出简单的答案,例如..
n=2438
n=str(n) # 2438 converted into "2438"
total_sum_of_digit=0
for i in n: # loop runs as it converted into string..
total_sum_of_digit+=int(i) #converted string digit to int digit and add into total_sum_of_digit
print(total_sum_of_digit)
列表理解是更好的选择..但你应该从初学者的角度去了解上述主题..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.