4

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

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.

Thanks.

Amanda
  • 51
  • 1
  • 1
  • 2
  • 1
    `balance += deposit` – Christian Dean Aug 17 '17 at 20:25
  • 2
    Since no one else has said this yet, I will: you would probably benefit hugely from an introduction-to-Python tutorial (eg. [this one](https://developers.google.com/edu/python/introduction) or [that one](https://www.youtube.com/watch?v=rkx5_MRAV3A)). StackOverflow doesn't teach you the basics of programming, it just gives specific answers to specific questions. – SwiftsNamesake Aug 17 '17 at 20:31

3 Answers3

12

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:

total = balance + deposit

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

balance += deposit

This is equivalent to doing:

balance = balance + deposit
stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53
  • Or assign it back to `balance`: `balance = balance + deposit` or `balance += deposit` – Fred Larson Aug 17 '17 at 20:26
  • Note that a += b is not always equivalent to a = a + b, they are equivalent for numbers, strings and tuples but not for lists. – plugwash Aug 09 '18 at 21:25
2

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

balance = 1000
deposit = 50
total = balance + deposit
print "Balance: " + str(total)
The_Outsider
  • 1,875
  • 2
  • 24
  • 42
0

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