首页 > 编程知识 正文

Python 程序:简单相加两个数字

时间:2023-11-24 15:33:37 阅读:308777 作者:QRVH

用例子写一个简单的 Python 程序。为了演示,我们将使用算术运算符将两个数字相加

简单的 Python 程序相加两个数字

这个简单的 Python 程序相加了两个数字,允许用户输入两个值。接下来,它将把这两个数字相加,并将总和赋给变量 sum。

number1 = input(" Please Enter the First Number: ")
number2 = input(" Please Enter the second number: ")

# Using arithmetic + Operator to add two numbers
sum = float(number1) + float(number2)
print('The sum of {0} and {1} is {2}'.format(number1, number2, sum))

Python 相加两个数字输出

 Please Enter the First Number: 22
 Please Enter the second number: 44
The sum of 22 and 44 is 66.0

在这个相加两个数字的简单 python 程序示例中,以下语句要求用户输入两个整数,并将用户输入的值存储在变量 1 和 2 中

number1 = input(" Please Enter the First Number: ")
number2 = input(" Please Enter the second number: ")

下一行,我们使用 Python 算术运算符“+”将数字 1 和数字 2 相加,然后将该总和赋给 sum。

从下面的语句中,您可以看到,我们使用 float type cast 将用户输入值转换为 float。这是因为,默认情况下,用户输入的值是字符串类型的,如果我们在两个字符串值之间使用+运算符,python 会连接这两个值,而不是相加它们

sum = float(number1) + float(number2)

下面的 Python 打印语句将输出 sum 变量(22 + 44 = 66)。

print('The sum of {0} and {1} is {2}'.format(number1, number2, sum))

这个 python 程序在加两个正整数的时候加两个数字效果很好,加正负整数怎么样?让我们看看

相加两个数字的示例 Python 程序示例 2

负数也没问题!。编写上述 python 相加两个数字程序的替代方法是:

number1 = float(input(" Please Enter the First Number: "))
number2 = float(input(" Please Enter the second number: "))

# Using arithmetic + Operator to add two numbers
sum = number1 + number2
print('The sum of {0} and {1} is {2}'.format(number1, number2, sum))
 Please Enter the First Number: 25
 Please Enter the second number: 91
The sum of 25.0 and 91.0 is 116.0

注:以上简单的程序将限制用户,不输入字符串值作为输入

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。