新聞中心
創(chuàng)新互聯(lián)Python教程:

在這個簡單的 python 程序中,我們必須找到一個數(shù)字的十進制位總和。這是一個初級 python 程序。
要理解這個例子,您應(yīng)該了解以下 Python 編程主題:
- Python 語法
- Python 循環(huán)
- Python 運算符
如何求一個數(shù)的位數(shù)之和?
在這個關(guān)于數(shù)字的基本 python 程序中,我們需要計算一個數(shù)字的十進制位總和,這意味著,取一個數(shù)字 123,我們必須找到總和為‘1+2+3 = 6’
要在這個簡單的 python 程序中應(yīng)用這個邏輯,我們需要打開一個while loop 直到數(shù)字小于零。我們必須使用 mod 運算符從數(shù)字中提取數(shù)字,并在 python 中計算總和為總和+數(shù)字。然后,我們必須通過將數(shù)字除以 10 來刪除數(shù)字中的一個數(shù)字。最后,我們用 python 語言打印 while 循環(huán)所有迭代后的結(jié)果。
算法
步驟 1: 使用輸入函數(shù)接受用戶的輸入,并使用 Python 編程語言中的int()將該字符串轉(zhuǎn)換為整數(shù)。
步驟 2: 將和初始化為零。
第三步:打開一個while loop直到數(shù)字小于零。
步驟 4: 使用模塊運算符從數(shù)字中提取一個數(shù)字。
第五步:計算總和為總和+數(shù)字。
第 6 步:將數(shù)字除以 10,去掉數(shù)字。
步驟 7: 使用打印語句打印結(jié)果。
Python 源代碼
n=int(input("Enter a number:"))
sum=0
while(n>0):
dig=n%10
sum=sum+dig
n=n//10
print("The sum of digits in the number is:",sum)
輸出
Enter a number : 123
The sum of digits in the number is: 6 文章標題:Python程序:計算一個數(shù)字的十進制位總和
轉(zhuǎn)載源于:http://m.fisionsoft.com.cn/article/dpsjjcp.html


咨詢
建站咨詢
