tom606060
tom606060

Reputation: 3

How do I accomplish the same thing without using a global variable?

add_digits2(1)(3)(5)(6)(0) should add up all the numbers and stop when it reaches 0. The output should be 15

The below code works but uses a global variable.

total = 0
def add_digits2(num):
    global total
    if num == 0:
        print(total)
    else:
        total += num
        return add_digits2

The result is correct but needs to do the same thing without using the global variable.

Upvotes: 0

Views: 58

Answers (4)

wwii
wwii

Reputation: 23773

Really hard to say what they are after when asking questions like that but the total could be stored in a function attribute. Something like this

>>> def f():
...     f.a = 3


>>> f()
>>> f.a
3

Upvotes: 0

Thierry Lathuille
Thierry Lathuille

Reputation: 24280

You could also use a class, using the __call__ method to obtain this behavior:

class Add_digits:

    def __init__(self):
        self.total = 0

    def __call__(self, val):
        if val != 0:
            self.total += val
            return self
        else:
            print(self.total)
            self.total = 0


add_digits = Add_digits()

add_digits(4)(4)(0)
# 8
add_digits(4)(6)(0)
# 10 

though I still don't get why you would want to do this...

Upvotes: 1

Sayse
Sayse

Reputation: 43320

You can just pass in *args as a parameter and return the sum

def add_digits2(*args):
     return sum(args)

add_digits2(1, 3, 5 ,6)

Upvotes: 1

Stefan Falk
Stefan Falk

Reputation: 25457

One thing you could do is use partial:

from functools import partial

def add_digits2(num, total=0):
    if num == 0:
        print(total)
        return
    else:
        total += num
        return partial(add_digits2, total=total)

add_digits2(2)(4)(0)

Upvotes: 3

Related Questions