0

I'm trying to make a simple adding function here. I start a count at 0. I want to add the argument of add_credits(x) to the credit total, to keep a running total. A for loop doesn't seem like the right thing to use here, since I don't know how many times I'll be looping.

So what I want to do here is, add 3. Credits = 3. Add 4, credits = 7.

credits = 0
def add_credits(x):
    new_total = credits + x
    return new_total

print (add_credits(3))
print (add_credits(4)) 

I know the solution must be really simple... I feel like an idiot.

4
  • Functions aren't meant to be used like this. You'd be better served by making a class instead. Commented Feb 17, 2018 at 22:17
  • You never even try to change the value of credits. Commented Feb 17, 2018 at 22:18
  • @IgnacioVazquez-Abrams why are functions not meant to be used like this? Commented Feb 18, 2018 at 0:47
  • They are meant to optionally accept arguments and return a result, without side effects. There are other constructs that can be used if side effects are required. Commented Feb 18, 2018 at 0:49

4 Answers 4

3

You can use a class to represent some sort of "Wallet" object. This will hold an attribute of total and an add function:

class Wallet:
    def __init__(self):
        self.total = 0

    def add_to_total(self, amount):
        self.total += amount


wallet = Wallet()
wallet.add_to_total(5)
print(wallet.total) # outputs 5
Sign up to request clarification or add additional context in comments.

Comments

1

in your example, the credits variable in the function is a local variable. This means it does not share the same value you assigned it at the top. You need to identify it as global for it to work like this:

credits = 0
def add_credits(x):
    global credits
    credits = credits + x
    return credits 

print (add_credits(3))
print (add_credits(4))

Comments

0

Code within a function will not change the value of a variable passed to it when the variable represents an int.

Comments

0

If you really want to increment the credits variable within the function, you can use global:

credits = 0


def add_credits(x):
    global credits
    credits += x


add_credits(3)
print(credits) # 3

add_credits(4)
print(credits) # 7

But using global in this way is not recommended, so I would definitely use Evyatar's solution.

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.