在這個簡單的 python 程序中,我們需要連接數字並計算總和。這是一個初級 python 程序。
要理解這個例子,您應該了解以下 Python 編程主題:
- Python 語法
- 蟒蛇串
- Python 運算符
python 中如何連接數字並計算和?
在這個 number python 程序示例中,我們需要使用 n + nn + nnn 的模式來找到數字 n 的連接總和。例如,讓我們取一個數字 5,我們必須使用模式 5 + 55 + 555 = 615。
為了解決 python 問題,我們首先需要將數字「n」更改為字元串。然後,我們將字元串「n」連接成「nn」和「nnn 」,然後將字元串轉換回一個數字,並計算連接數字的總和,然後列印結果。
我們使用 python 語言的int
和str
函數將字元串轉換為整數,再將整數轉換為字元串。使用一個 temp 變數來存儲字元串數字,然後我們將 temp + temp 連接到另一個變數。並將 temp + temp + temp 轉換為另一個變數。最後,我們通過使用 int 將字元串轉換為整數來計算和。
演算法
步驟 1: 使用輸入法輸入數字,並使用 python 編程中的int()
將該輸入字元串轉換為整數。
步驟 2: 將整數轉換為字元串,並將該值存儲在變數中進行連接。
步驟 3: 使用 temp + temp 和 temp + temp 連接字元串後,使用兩個變數存儲值。
STEP 4: 現在我們有了字元串,並使用int()
將字元串轉換為數字,並使用 python 語言計算總和。
STEP 5: 使用 python basics 中的 Print 語句列印結果的值。
Python 源代碼
n=int(input("Enter a number n: "))
temp=str(n)
t1=temp+temp # concatenate the strings
t2=temp+temp+temp
comp=n+int(t1)+int(t2) # calculate the sum
print("The sum is:",comp)
輸出
Enter the Number n : 5
The sum is : 615
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/297747.html