Variables and Functions explanation for a beginner
Question:
I don’t know how functions work and would like help making sure that I can have the variable change depending on which ‘person’ is running the account. Can someone explain how to change the ‘bad’ variable so that it goes to a ‘person 1’ ‘person 2’ or ‘person 3’ depending on which the user chooses to enter?:
bal=500
lock=0
end=False
def atm():
while end==False:
if lock>=4:
while lockloop==True:
try:
print("Your balance is $",bal, sep='')
lk=int(input("Error, you have locked your account. Please enter funds until balance becomes positive: n$"))
if lk<=0:
print("Please input a positive amount")
continue
bal=bal+lk
if bal<0:
continue
except ValueError:
print("Try again")
continue
else:
lockloop=False
lk=0
lock=0
print("Your balance is now: $", bal, sep='')
des=input("Would you like to (d)eposit, (w)ithdraw, (b)alance, or (e)nd? ")
witloop=True
deploop=True
lockloop=True
if lock>1 and bal>=0:
lock=1
if des=="deposit" or des=="d" and lock<4:
while deploop==True:
try:
dep=int(input("How much would you like to deposit? "))
if dep<=0:
print("Please input a positive amount")
continue
except ValueError:
print("Try again")
continue
else:
deploop=False
bal=dep+bal
dep=0
if bal<0 and lock==0:
bal=bal-50
lock=lock+1
print("You have incured an overdraft fee of $50. It will be removed from your account.")
if bal<0 and lock!=0:
lock=lock+1
print("Your account is still overdrawn. Please deposit funds.")
print("You now have: $", bal, sep='')
continue
elif des=="withdraw" or des=="w" and lock<4:
if bal<=0:
print("Cannot withdraw funds at this time.")
continue
while witloop==True:
try:
wit=int(input("How much would you like to withdraw? "))
if wit<=0:
print("Please input a positive amount")
continue
except ValueError:
print("Try again")
continue
else:
witloop=False
bal=bal-wit
wit=0
if bal<0 and lock==0:
bal=bal-50
lock=lock+1
print("You have incured an overdraft fee of $50. It will be removed from your account.")
if bal<0 and lock!=0:
lock=lock+1
print("Your account is still overdrawn. Please deposit funds.")
print("You now have: $", bal, sep='')
continue
elif des=="balance" or des=="b":
print("You have: $", bal, sep='')
continue
elif des=="end" or des=="e" and lock==0:
end=True
print("Thank you for banking with Nolan's Banking Services today! Have a great day! :)")
else:
print("You must enter one of the four options, try again")
continue
atm()
Answers:
Running your code as-is is returning this error:
UnboundLocalError: local variable 'end' referenced before assignment
The reason here is to do with the scope of your variables. You are declaring the bal
, lock
and end
variables outside of your function, therefore making them global variables. But you are also then declaring those variables inside the function, making them local variables. The interpreter is getting confused and the error is telling you the the local variable end
is being used before it is being assigned.
Don’t mix and match variables inside and outside a function like this. You should try to avoid global variables in your functions as much as possible as a good rule of thumb when programming.
You could read some more here as a starting point:
https://www.w3schools.com/python/python_variables_global.asp
https://bobbyhadz.com/blog/python-unboundlocalerror-local-variable-name-referenced-before-assignment
I don’t know how to have the function use a different variable for each person
You can pass arguments into your function like this. In this case, when we define the function, we tell it to expect an argument called user
that you can then use inside your function.
def atm(user):
if user == 'Nolan':
print('Hi Nolan')
elif user == 'Lummers':
print('Hi Lummers')
else:
print("I don't talk to strangers")
atm('Nolan')
atm('Lummers')
atm('John Doe')
To provide a different variable for each person I suggest you look into classes. Something like …
class Person:
def __init__(self, name: str, balance: float = 0):
"""Create a new person each time."""
self.name = name
self.balance = balance
def action(self, action: str, amount: float):
if action == 'deposit':
self.balance += amount
elif action == 'withdraw':
self.balance -= amount
def __repr__(self):
return f"{self.name} {self.balance}"
def main():
customers = {}
customers['Fred'] = Person('Fred', 500)
customers['Jane'] = Person('Jane')
"""Preload some actions for example."""
actions = [
['Fred', 'withdraw', 123],
['Jane', 'deposit', 789]
]
"""Process the actions. Could run forever."""
for person, action, value in actions:
if person in customers:
customers[person].action(action, value)
print(customers)
if __name__ == '__main__':
main()
I don’t know how functions work and would like help making sure that I can have the variable change depending on which ‘person’ is running the account. Can someone explain how to change the ‘bad’ variable so that it goes to a ‘person 1’ ‘person 2’ or ‘person 3’ depending on which the user chooses to enter?:
bal=500
lock=0
end=False
def atm():
while end==False:
if lock>=4:
while lockloop==True:
try:
print("Your balance is $",bal, sep='')
lk=int(input("Error, you have locked your account. Please enter funds until balance becomes positive: n$"))
if lk<=0:
print("Please input a positive amount")
continue
bal=bal+lk
if bal<0:
continue
except ValueError:
print("Try again")
continue
else:
lockloop=False
lk=0
lock=0
print("Your balance is now: $", bal, sep='')
des=input("Would you like to (d)eposit, (w)ithdraw, (b)alance, or (e)nd? ")
witloop=True
deploop=True
lockloop=True
if lock>1 and bal>=0:
lock=1
if des=="deposit" or des=="d" and lock<4:
while deploop==True:
try:
dep=int(input("How much would you like to deposit? "))
if dep<=0:
print("Please input a positive amount")
continue
except ValueError:
print("Try again")
continue
else:
deploop=False
bal=dep+bal
dep=0
if bal<0 and lock==0:
bal=bal-50
lock=lock+1
print("You have incured an overdraft fee of $50. It will be removed from your account.")
if bal<0 and lock!=0:
lock=lock+1
print("Your account is still overdrawn. Please deposit funds.")
print("You now have: $", bal, sep='')
continue
elif des=="withdraw" or des=="w" and lock<4:
if bal<=0:
print("Cannot withdraw funds at this time.")
continue
while witloop==True:
try:
wit=int(input("How much would you like to withdraw? "))
if wit<=0:
print("Please input a positive amount")
continue
except ValueError:
print("Try again")
continue
else:
witloop=False
bal=bal-wit
wit=0
if bal<0 and lock==0:
bal=bal-50
lock=lock+1
print("You have incured an overdraft fee of $50. It will be removed from your account.")
if bal<0 and lock!=0:
lock=lock+1
print("Your account is still overdrawn. Please deposit funds.")
print("You now have: $", bal, sep='')
continue
elif des=="balance" or des=="b":
print("You have: $", bal, sep='')
continue
elif des=="end" or des=="e" and lock==0:
end=True
print("Thank you for banking with Nolan's Banking Services today! Have a great day! :)")
else:
print("You must enter one of the four options, try again")
continue
atm()
Running your code as-is is returning this error:
UnboundLocalError: local variable 'end' referenced before assignment
The reason here is to do with the scope of your variables. You are declaring the bal
, lock
and end
variables outside of your function, therefore making them global variables. But you are also then declaring those variables inside the function, making them local variables. The interpreter is getting confused and the error is telling you the the local variable end
is being used before it is being assigned.
Don’t mix and match variables inside and outside a function like this. You should try to avoid global variables in your functions as much as possible as a good rule of thumb when programming.
You could read some more here as a starting point:
https://www.w3schools.com/python/python_variables_global.asp
https://bobbyhadz.com/blog/python-unboundlocalerror-local-variable-name-referenced-before-assignment
I don’t know how to have the function use a different variable for each person
You can pass arguments into your function like this. In this case, when we define the function, we tell it to expect an argument called user
that you can then use inside your function.
def atm(user):
if user == 'Nolan':
print('Hi Nolan')
elif user == 'Lummers':
print('Hi Lummers')
else:
print("I don't talk to strangers")
atm('Nolan')
atm('Lummers')
atm('John Doe')
To provide a different variable for each person I suggest you look into classes. Something like …
class Person:
def __init__(self, name: str, balance: float = 0):
"""Create a new person each time."""
self.name = name
self.balance = balance
def action(self, action: str, amount: float):
if action == 'deposit':
self.balance += amount
elif action == 'withdraw':
self.balance -= amount
def __repr__(self):
return f"{self.name} {self.balance}"
def main():
customers = {}
customers['Fred'] = Person('Fred', 500)
customers['Jane'] = Person('Jane')
"""Preload some actions for example."""
actions = [
['Fred', 'withdraw', 123],
['Jane', 'deposit', 789]
]
"""Process the actions. Could run forever."""
for person, action, value in actions:
if person in customers:
customers[person].action(action, value)
print(customers)
if __name__ == '__main__':
main()