1

I'm having an issue because i have to run the same function many times and want to record a total for every time it was run.

def add(word):
    total_hello=0
    total_world=0
    if word=="hello":
       total_hello+=1
    elif word=="world":
       total_world+=1

    print(total_hello)
    print(total_world)
    return total_hello, total_world

hello=0
world=0
hello, world+=add("hello")
hello, world+=add("world")
hello, world+=add("hello")
print(hello)
print(world)

Making hello a variable and trying to make it += the return doesn't work. Is there anything simple i can do to add the returns efficiently?

FATCAT47
  • 40
  • 10
  • 2
    `hello, world` makes a tuple. You can't use `+=` like that to add from a tuple to a tuple. – Mark Apr 20 '20 at 04:54
  • 1
    if you redefine the `+=` then you can, but not in the vanilla form – Bryce Wayne Apr 20 '20 at 04:55
  • 1
    Please add the traceback so we see the exact error. Also, what would you like to happen? Do you want to add the 2 output values to `hello` and `world`? – tdelaney Apr 20 '20 at 04:56
  • 1
    Use global variables or pass the variable reference to the function and update them. – thuva4 Apr 20 '20 at 04:59

2 Answers2

1

Making hello a variable and trying to make it += the return doesn't work. Is there anything simple i can do to add the returns efficiently?

You can't just add the elements of tuple returned by your function to the tuple's element on left-hand side. You have following options:

  1. The variables (total_hello and total_world) are local to your function and they are reassigned every-time you call your function to 0. Try moving them outside your function and make them global. They can be used to store the count of the variables.
# Code in Module 1:
total_hello=0
total_world=0

def add(word):
    global total_hello, total_world
    if word=="hello":
       total_hello+=1
    elif word=="world":
       total_world+=1

    return total_hello, total_world


# Code in Module 2:
# from Module1 import *
add("hello")
add("world")
hello, world = add("hello")
print(hello)
print(world)

  1. See this answer for a more Pythonic way.

  2. Using default arguments in Python:

def add(word, total_world=[0], total_hello=[0]):
    if word == "hello":
       total_hello[0] += 1
    elif word == "world":
       total_world[0] += 1

    return total_hello[0], total_world[0]


add("hello")
add("world")
hello, world = add("hello")
print(hello)
print(world)
abhiarora
  • 9,743
  • 5
  • 32
  • 57
1

You can directly use hello and world inside function.

hello=0
world=0
def add(word):
    global hello, world
    if word=="hello":
       hello+=1
    elif word=="world":
       world+=1

    print(hello)
    print(world)

add("hello")
add("world")
add("hello")

print(hello)
print(world)
Prudhvi
  • 1,095
  • 1
  • 7
  • 18