Droxbot
Droxbot

Reputation: 53

Modifying a variable from one function to another in Python

Here are the functions in question:

def ATM():
    global mode
    pinNum = input('Please enter your 4 digit secret code: ')
    userBalance = float(dict2[pinNum])
    while mode == 0:
        if pinNum in dict1:
            greet = input('Hello {}, please enter 1 to check your balance, 2 to make a withdrawal, 3 to make a deposit, or 4 to end your session: '.format(dict1[pinNum]))
        if greet == '1':
            balance(userBalance)
        elif greet == '2':
            withdraw(userBalance)
        elif greet == '3':
            deposit(userBalance)
        elif greet == '4':
            mode = 1

def balance(userBalance):
    print('Your current balance is {}.'.format(userBalance))


def deposit(userBalance):
    amount = input('Please enter the amount you wish to be deposited: ')
    userBalance += float(amount)
    return userBalance


def withdraw(userBalance):
    amount = input('Please enter the amount you wish to withdraw" ')
    if userBalance - float(amount) < 0:
             print('You do not have sufficient funds.')
    else:
        userBalance -= float(amount)

I am having trouble making adjustments to the balance when I call the deposit or withdraw function within ATM(). I am thinking I may not be returning the data correctly in the deposit and withdraw functions. This program is simulating an ATM for reference and dict1 and dict2 are defined outside the functions. Any help is appreciated.

Upvotes: 0

Views: 50

Answers (1)

yograterol
yograterol

Reputation: 603

I think that this can help you:

def ATM():
    global mode
    pinNum = input('Please enter your 4 digit secret code: ')
    userBalance = float(dict2[pinNum])
    actions = {
        '1': balance,
        '2': withdraw,
        '3': deposit
    }
    while mode == 0:
        if pinNum in dict1:
            greet = input('Hello {}, please enter 1 to check your balance, 2 to make a withdrawal, 3 to make a deposit, or 4 to end your session: '.format(dict1[pinNum]))
        if greet == '4':
            break
        else:
            userBalance = actions.get(greet)(userBalance) or userBalance

def balance(userBalance):
    print('Your current balance is {}.'.format(userBalance))


def deposit(userBalance):
    amount = input('Please enter the amount you wish to be deposited: ')
    userBalance += float(amount)
    return userBalance


def withdraw(userBalance):
    amount = input('Please enter the amount you wish to withdraw" ')
    if userBalance - float(amount) < 0:
             print('You do not have sufficient funds.')
    else:
        userBalance -= float(amount)
    return userBalance

Upvotes: 1

Related Questions