Python:如何将带有整数值的变量相加?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45744364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:15:36  来源:igfitidea点击:

Python: How do I add variables with integer values together?

python

提问by Amanda

I'm new to Python. How do I add variables with integer values together?

我是 Python 的新手。如何将具有整数值的变量相加?

balance = 1000
deposit = 50
balance + deposit
print "Balance: " + str(balance)

I want balance and deposit to add together to it 1050, but I'm just getting 1000. I know I'm clearly not formatting it (balance + deposit) correctly, but I can't figure out the right way to format it.

我希望余额和存款加起来为 1050,但我刚得到 1000。我知道我显然没有正确格式化它(余额 + 存款),但我无法弄清楚格式化它的正确方法。

Thanks.

谢谢。

回答by stybl

Doing this:

这样做:

balance + deposit

Does the addition and returns the result (1050). However, that result isn't stored anywhere. You need to assign it to a variable:

进行加法并返回结果 (1050)。但是,该结果不会存储在任何地方。您需要将其分配给一个变量:

total = balance + deposit

Or, if you want to increment balanceinstead of using a new variable, you can use the +=operator:

或者,如果您想增加balance而不是使用新变量,您可以使用+=运算符

balance += deposit

This is equivalent to doing:

这相当于做:

balance = balance + deposit

回答by The_Outsider

You need to assign the sum to a variable before printing.

您需要在打印之前将总和分配给一个变量。

balance = 1000
deposit = 50
total = balance + deposit
print "Balance: " + str(total)

回答by Marco Simone

you need to use the assignment operator: balance = balance + deposit OR balance += deposit

您需要使用赋值运算符: balance = balance + deposit OR balance += deposit