-2

In this code I tried to make that when you type "work", you get any number from 1 to 50 and it adds itself to the total balance (5 times). But when I do this, the previous amount of the variable resets to the new amount.

import random
balance = 0
def work(balance):
    earned_money = random.randint(1, 50)
    balance += earned_money
    print(balance)
for x in range(5):
    user_input = input()
    if user_input == "work":
        work(balance)
jgames07
  • 48
  • 1
  • 9
  • The `balance` variable inside the function is not the same as the global variable. – Barmar Jun 05 '21 at 20:07
  • 1
    You're adding to the local variable, that doesn't affect the global variable. – Barmar Jun 05 '21 at 20:07
  • Does this answer your question? [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – SuperStormer Jun 05 '21 at 20:08

3 Answers3

1

Even though the global keyword solves your problem, depending on who you ask, global variables are considered bad practice in Python. I try to avoid them unless there's absolutely no other way, and in this case, it's quite easy to come up with a solution that doesn't need globals:

import random

balance = 0

def work(balance):
    earned_money = random.randint(1, 50)
    return balance + earned_money

for x in range(5):
    user_input = input()
    if user_input == "work":
        balance = work(balance)
        print(balance)

fsimonjetz
  • 5,644
  • 3
  • 5
  • 21
0

I recommend learning more about variable scope.

Here is working code. You need to declare it as global.

import random

balance = 0

def work():
    global balance
    earned_money = random.randint(1, 50)
    balance += earned_money
    print(balance)

for x in range(5):
    user_input = input()
    if user_input == "work":
        work()
Teejay Bruno
  • 1,716
  • 1
  • 4
  • 11
  • Thanks for your answer. The global keyword resolved the problem, even though when I tried the code it didn't work, I just had to remove both `balance` in the `work` parenthesis. – jgames07 Jun 05 '21 at 20:22
  • Using global variables, though it may quickly solve the problem, is generally a bad idea and ultimately leads to poor code, difficult to test and prone to errors. It is much better to pass the variable and affect the function output to it, as in @fsimonjetz's answer. – Thierry Lathuille Jun 05 '21 at 20:46
0

The outer balance variable is in global scoping whereas the balance variable inside function is in local scoping. If you want to make local scope variable global then you need to use global keyword inside your function.

import random
balance = 0

def work():
    global balance   # This makes balance variable global.
    earned_money = random.randint(1, 50)
    balance += earned_money
    print(balance)

for x in range(5):
    user_input = input()
    if user_input == "work":
        work()
Ghantey
  • 626
  • 2
  • 11
  • 25