Python 程序:连接数字并计算 n+nn+nnn


2022年3月9日, Learn eTutorial
1790

在这个简单的 Python 程序中,我们需要连接数字并计算它们的和。这是一个初级的 Python 程序。

要理解这个例子,您应该了解以下 Python 编程主题

如何在 Python 中连接数字并计算它们的和?

在这个 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:使用 input 方法输入数字,并使用 Python 编程中的 `int()` 将该输入字符串转换为整数。

步骤 2:将整数转换为字符串,并将该值存储在一个变量中以进行连接。

步骤 3:使用两个变量存储使用 **temp + temp 和 temp + temp + temp** 连接字符串后的值。

步骤 4:现在我们有了字符串,使用 `int()` 将字符串转换为数字,并使用 Python 语言计算和。

步骤 5:使用 Python 基础中的 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