简体   繁体   中英

How to add to an already existing variable in python?

I know this is a very simple question, but I couldn't find it. Basically what I'm trying to is have a=2 , b=3 , and I need a+b=b so when I add a and b what it equals needs to be b .

Either:

b = a + b
# make b equal to a + b

Or

b += a
# increase the value of b by a

declare variables

a = 2
b = 3

operates

b = a+b

You can use the += shorthand for summation on variable.

For instance, in order to add in the value of a in the b variable, and retaining the last value of b :

b += a

This is the same thing as saying: b = a + b . Both works fine. Choose as you feel is readable.

Here is a quick example:

First, initialize your variables:

a = 2
b = 3
print a, b 

Output: 2 3

You can add a to b, this way:

b += a
print b

Output: 5

You can also add to the actual value of b 10

b = 10+b
print b

Output: 15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM