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.

2
  • 1
    balance += deposit Commented Aug 17, 2017 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 or that one). StackOverflow doesn't teach you the basics of programming, it just gives specific answers to specific questions. Commented Aug 17, 2017 at 20:31

3 Answers 3

11

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
Sign up to request clarification or add additional context in comments.

2 Comments

Or assign it back to balance: balance = balance + deposit or balance += deposit
Note that a += b is not always equivalent to a = a + b, they are equivalent for numbers, strings and tuples but not for lists.
2

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.