0

I have this piece of code here. Let's focus on the total variable.

def start():
    global total
    total = "$" + str(input("Please enter the amount you want set as your total"))
    if total < 0:
        print("no negative values, try again.")
        start()
    else:
        bets()

Would it be better to return this variable or turn it into a global variable like I already did: global total. Both the return and global keywords feature very similar use cases and so I was wondering whether I should worry about choosing which way I should make that variable accessible to other code

  • 3
    `return` it. `global` is the wrong choice 99.9% of the time. – Samwise Aug 06 '22 at 21:32
  • is there a particular reason? –  Aug 06 '22 at 21:32
  • 2
    One big problem with `global` (among *many* problems) is that the caller has no control over where the output goes; your function might even accidentally overwrite a variable that the caller itself was using for something else! I'm pretty sure if you google "why is global bad in python" you'll find many many articles explaining the many other reasons. :) – Samwise Aug 06 '22 at 21:34
  • @programmingnoob1234590 because global mutable state is a well-known antipattern: https://softwareengineering.stackexchange.com/a/148109/337977 For small programs, it's not a big, but as soon as it starts getting bigger, it becomes a big problem. You should get out of the habit of relying on mutable global state – juanpa.arrivillaga Aug 06 '22 at 21:47

0 Answers0