Home > front end >  How do I create a variable that can be changed by calling a function in Python but also saves the da
How do I create a variable that can be changed by calling a function in Python but also saves the da

Time:09-14

For example, let's say I'm trying to create a wallet system in python where money can be add to and taken out of. I try this code here:

balance = 0
def addmoney(x):
    x  = balance
addmoney(10000)
print(balance)

but it just gave me 0. so then I tried this:

def addmoney(x):
    balance = 0 
    balance  = x

And I realized that this would set the money back to 0 every time the user adds money, which I didn't want. Is there a solution to this?

CodePudding user response:

You could declare the balance variable as global inside the function.

balance = 0
def addmoney(x):
    global balance
    balance  = x
addmoney(10000)
print(balance)

CodePudding user response:

This is usually do with OOP:

class BankAccount:

    def __init__(self, owner, balance, currency):
        self.owner = owner
        self.balance = balance
        self.currency = currency

    def print_balance(self):
        print("Your current balance is:")
        print(self.balance)

    def make_deposit(self, amount):
        if amount > 0:
            self.balance  = amount
        else:
            print("Please enter a valid amount.")

    def make_withdrawal(self, amount):
        if self.balance - amount >= 0:
            self.balance -= amount
        else:
            print("You don't have enough funds to make this withdrawal.")

To call the function:

my_savings_account = BankAccount("Pepita Perez", 45600, "USD")
my_savings_account.print_balance()
my_savings_account.make_deposit(5000)
my_savings_account.make_withdrawal(200)
my_savings_account.print_balance()

CodePudding user response:

In Python, you must use the global keyword when accessing global variables from within a function. See here.

One way to keep track of the changes is to store the previous values in a list outside the function. Again, using the global keyword

Also your logic for the balance is backwards. You should be adding x to the balance.

balance = 0
historyLst = []
def addmoney(x):
    global balance
    global historyLst
    historyLst.append(balance)
    balance  = x
    
addmoney(10000)
print(balance)
  • Related