Python ATM Else and Elif Errors - python

I've been having some trouble with Else and Elif statements in Python 3.3.3 lately.
Here's my code:
# ATM was programmed by Jamie Mathieson
# introduction
sleep (1)
print ("-----------------------------------------------")
print ("\n ATM ")
print ("\n-----------------------------------------------")
sleep (3)
print ("\nWelcome to ATM. ATM is a mathematical system that handles data.")
sleep (5)
print ("\n Your ATM card has is being inserted. Please wait...")
sleep (3)
print ("Your ATM card has been inserted.")
sleep (5)
print ("Type 'options' to view available commands.")
# variables
balance = print("Balance £", money)
money = 200
options = ("Options: 1) Withdraw <amount> 2) Deposit <amount> 3) Balance 4) Exit")
# statements
option=int(input("Please enter an option: "))
if Option==1:
print("Balance £", money)
if Option==2:
print("Balance £", money)
Withdraw=float(input("Please enter the amount of money you would like to withdraw: £ "))
if Withdraw>0:
newbalance=(money-Withdraw)
print("New Balance: £",remainingbalance)
elif: Withdraw>money
print("No Balance Remaining")
else:
print("Withdraw canceled.")
if Option==3:
print("Balance £", money)
Deposit=float(input("Please enter the amount of money you would like to deposit: £ "))
if Deposit>0:
newbalance=(money+Deposit)
print("New Balance: £",newbalance)
else:
print("Deposit canceled.")
if Option==4:
print("ATM is ejecting your card. Please wait...")
sleep(5)
exit()
The error I'm getting is "invalid syntax" and it highlights both the Else and Elif statements. What is it that I'm doing wrong?

You have to put the : at the end, and correct the identation.
if Option==2:
print("Balance £", money)
Withdraw=float(input("Please enter the amount of money you would like to withdraw: £ "))
if Withdraw>0:
newbalance=(money-Withdraw)
print("New Balance: £",remainingbalance)
elif Withdraw>money:
print("No Balance Remaining")
else:
print("Withdraw canceled.")

There are several issues with the code. As #Daniel pointed out, your indentation must be corrected. Also, your condition for the elif block is placed after the colon.
Beyond that, you're assigning the user's response to a variable called option and then writing conditions on Option. Those are two different things.
Finally balance = print("Balance £", money) is going to throw an error. It looks like you're trying to define balance as a function that will print "Balance £" followed by the balance amount. If so, you could do something like this:
balance = lambda x: print("Balance £{}".format(x))
Edit: To answer your question re: sleep, use
from time import sleep

while True:
# Reading id from user
id = int(input("\nEnter account pin: "))
# Loop till id is valid
while id < 1000 or id > 9999:
id = int(input("\nInvalid Id.. Re-enter: "))
# Iterating over account session
while True:
# Printing menu
print("\n1 - View Balance \t 2 - Withdraw \t 3 - Deposit \t 4 - Exit ")
# Reading selection
selection = int(input("\nEnter your selection: "))
# Getting account object
for acc in accounts:
# Comparing account id
if acc.getId() == id:
accountObj = acc
break
# View Balance
if selection == 1:
# Printing balance
print(accountObj.getBalance())
# Withdraw
elif selection == 2:
# Reading amount
amt = float(input("\nEnter amount to withdraw: "))
ver_withdraw = input("Is this the correct amount, Yes or No ? " + str(amt) + " ")
if ver_withdraw == "Yes":
print("Verify withdraw")
else:
break
if amt < accountObj.getBalance():
# Calling withdraw method
accountObj.withdraw(amt)
# Printing updated balance
print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n")
else:
print("\nYou're balance is less than withdrawl amount: " + str(accountObj.getBalance()) + " n")
print("\nPlease make a deposit.");
# Deposit
elif selection == 3:
# Reading amount
amt = float(input("\nEnter amount to deposit: "))
ver_deposit = input("Is this the correct amount, Yes, or No ? " + str(amt) + " ")
if ver_deposit == "Yes":
# Calling deposit method
accountObj.deposit(amt);
# Printing updated balance
print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n")
else:
break
elif selection == 4:
print("nTransaction is now complete.")
print("Transaction number: ", random.randint(10000, 1000000))
print("Current Interest Rate: ", accountObj.annualInterestRate)
print("Monthly Interest Rate: ", accountObj.annualInterestRate / 12)
print("Thanks for choosing us as your bank")
exit()
# Any other choice
else:
print("That's an invalid choice.")
# Main function
main()

Related

How to permanently change a variable in Python?

I decided to make a code in Python that is like an ATM Machine, and Everything works very well, you can check your balance, extract or add money,and change the PIN code. But when I change the PIN code i tried to assign the "changed_pin_code" variable to the "real_pin_code" variable,and it doesen't work, the PIN code remains the same. If you could give me some ideas on how I could solve the problem, or improve my code, that would be fantastic.
I am at the beggining with coding, and I am doing this so I can test my knowledge.
I left the code below.
def atm_machine():
code = input("Enter yout PIN code:")
pin_code = int(code)
real_pin_code = 4137
balance = 10000
if pin_code == real_pin_code:
print("""
ATM
1)Check Balance
2)Add money
3)Extract money
4)Change PIN code\n""")
number_select = int(input("Select a number:"))
if number_select > 4 and number_select == 0:
print("You must select a number between 1 and 4!")
atm_recall()
if number_select == 1:
print("Your current balance is:", balance, "$")
atm_recall()
if number_select == 2:
money_add = int(input("Enter amount of money you want to add:"))
new_money = balance + money_add
print("Your current balance is:", new_money, "$")
atm_recall()
if number_select == 3:
money_extract = int(input("Enter the amount of money you want to extract:"))
if money_extract > balance:
print("Insufficent fund")
atm_recall()
if money_extract <= balance:
remained_money = balance - money_extract
balance = remained_money
print("Your current balance is:", remained_money, "$")
atm_recall()
if number_select == 4:
measure_pin = 9999
changed_pin_code = int(input("Enter new PIN code:"))
if changed_pin_code == real_pin_code:
print("You can't enter the same PIN code:")
print("Wait for yout card!")
atm_recall()
if changed_pin_code > measure_pin:
print("PIN code must be formed of 4 digits!")
print("Wait for your card")
atm_recall()
else:
real_pin_code = changed_pin_code
print("PIN code succesfully changed!")
print("Your new PIN code is:", changed_pin_code)
atm_recall()
else:
print("PIN code inccorect!")
print("Wait for your card!")
def atm_recall():
question = str(input("To make another action, type \"Y\",else, type\"N\" "))
if question == "Y":
result = atm_machine()
return result
if question == "N":
print("Good Bye!")
print("Wait for your card!")
atm_machine()
The problem you are currently facing is because at end of each option you call atm_recall function, in which if the user selects the 'Y' option, it calls the atm_machine function which whenever called starts with real_pin_code set to 4137.
Solution:
As already mentioned by others, in comments what you should rather do is get rid of the recursion as it uses up a lot of memory and fills up the call stack on each function call. So a refactored approach would be something like this:
real_pin_code = 4137
balance = 10000
while True:
code = input("Enter yout PIN code:")
pin_code = int(code)
if pin_code == real_pin_code:
print("""
ATM
1)Check Balance
2)Add money
3)Extract money
4)Change PIN code\n""")
number_select = int(input("Select a number:"))
if number_select == 1:
print("Your current balance is:", balance, "$")
elif number_select == 2:
money_add = int(input("Enter amount of money you want to add:"))
balance = balance + money_add
print("Your current balance is:", balance, "$")
elif number_select == 3:
money_extract = int(input("Enter the amount of money you want to extract:"))
if money_extract > balance:
print("Insufficent fund")
else:
remained_money = balance - money_extract
balance = remained_money
print("Your current balance is:", remained_money, "$")
elif number_select == 4:
measure_pin = 9999
changed_pin_code = int(input("Enter new PIN code:"))
if changed_pin_code == real_pin_code:
print("You can't enter the same PIN code:")
print("Wait for yout card!")
elif changed_pin_code > measure_pin:
print("PIN code must be formed of 4 digits!")
print("Wait for your card")
else:
real_pin_code = changed_pin_code
print("PIN code succesfully changed!")
print("Your new PIN code is:", changed_pin_code)
else:
print("You must select a number between 1 and 4!")
else:
print("PIN code inccorect!")
print("Wait for your card!")
question = str(input("To make another action, type \"Y\",else, type\"N\" "))
if question == "N":
print("Good Bye!")
print("Wait for your card!")
break
Changes:
I took real_pin_code out of the loop, so its value doesn't reset at each iteration.
Also, for the same reason I took balance out of the loop and made the changes to balance itself rather than declaring a new variable new_money.
Also, as a good programming practice I changed a lot of if statements to elif and else where the conditions were exclusive of each other.
Better Approach:
A better approach, as already highlighted by others would be to use class where you would initialize an ATMMachine object with all the required details. However the approach you choose, mostly all the logic would remain the same except some refactoring and specific methods for each task.
I'm not sure if it's a best way to do it, but I would create a txt file with atm pin which You could read in the beggining to take pin code and write it when You want to change it. Something like this:
def atm_machine():
code = input("Enter yout PIN code:")
pin_code = int(code)
real_pin = open("code.txt", "r")
real_pin_code = int(real_pin.read())
Here I already have a txt file with some code created in program folder so python could read it, and here I'm saving new pin to same txt file:
else:
real_pin = open("code.txt", "w")
real_pin.write(str(changed_pin_code))
print("PIN code succesfully changed!")
print("Your new PIN code is:", changed_pin_code)
atm_recall()
Hope this helps anyhow.

Expected expression ATM

I was following along with a youtube video to a ATM using python and I got expected expression. I dont know how to fix it. line 32, 37 and 40.
enter image description here
You can't have an elif after an else. This is because else will capture all the remaining cases. Indentation, meaning spaces or tabs before the line is very important in Python.
Here is what I think you meant to write:
balance = 1000
print("""
Welcome to Dutch Bank
Choose Transaction
1) BALANCE
2) WITHDRAW
3) DEPOSIT
4) EXIT
""")
while True:
option = int(input("Enter Transaction"))
if option == 1:
print ("Your Balance is", balance)
anothertrans = input("Do You Want to make another Transaction? Yes/No: ")
if anothertrans == "YES":
continue
else:
break
elif option == 2:
withdraw = float(input("Enter Amount To Withdraw"))
if (balance > withdraw):
total = balance - withdraw
print("Success")
print("Your New Balance is: ",total)
else:
print("Insufficient Balance")
elif option == 3:
deposit = float(input("Enter Amount To Deposit"))
totalbalance = balance + deposit
print("Sucess")
print("Total Balance Now is: ", totalbalance)
elif option == 4:
print("Thank You ForBanking With Dutch Bank")
exit()
else:
print ("No selected Transaction")

Save a variable from a function to reuse when it loops

I just started to learn python yesterday so complete noob. I have about 10 hours javascript experience to but had to switch since I'm learning Python in college. I decided to try make a program by myself since I learn a lot better doing that instead of countless videos.
The major problem I'm having is saving my variable of balance. When I win or lose the balance just restarts at 2000. I think that's probably because of the variable balance = 2000 but if I don't define it, it doesn't work. I know it's not anything important but I want to learn where I'm going wrong.
If anyone can help me that would be much appreciated. Also I know the codes a mess but will try make it better later.
global balance
name = input ("Please Enter Your Name: ")
password = input ("Please Make A Password: ")
def playgame():
balance = 2000
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
if yesOrNo == "y":
howBigABet = int(input("How Much Would You like to bet?: "))
if howBigABet <= balance:
pickNumber = int(input("Please PicK A Number: "))
from random import randint
value = randint(0, 1)
print(value)
if pickNumber == value:
print(value)
balance = balance + howBigABet * 2
print("you won " + str(howBigABet * 2))
print(balance)
playgame()
else:
print ("Sorry Wrong Number")
balance = balance - howBigABet
print("your new balance is: " + str(balance))
playgame()
if balance <= 200:
print("You Are Low on Cash Top up?")
elif balance <= 0:
print("You Are Out Of cash " + name + " Top Up ")
playgame()
else:
print("Sorry You Dont Have Enough Money")
print("Hello " + name)
passwordAttempted = input("Please Enter Your Password: ")
if passwordAttempted == password:
print("Welcome " + name)
playgame()
else:
print ("Wrong Password " + name + " !")
You can just pass balance as an argument, to your playgame function
like this
def playgame(balance=2000):
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
...
And than just pass, the new balance to all the playgame calls
But a much better way than using a recurent function would be a while loop
name = input ("Please Enter Your Name: ")
password = input ("Please Make A Password: ")
def playgame(balance=2000):
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
if yesOrNo == "y":
howBigABet = int(input("How Much Would You like to bet?: "))
if howBigABet <= balance:
pickNumber = int(input("Please PicK A Number: "))
from random import randint
value = randint(0, 1)
print(value)
if pickNumber == value:
print(value)
balance = balance + howBigABet * 2
print("you won " + str(howBigABet * 2))
print(balance)
return balance
else:
print ("Sorry Wrong Number")
balance = balance - howBigABet
print("your new balance is: " + str(balance))
return balance
if balance <= 200:
print("You Are Low on Cash Top up?")
elif balance <= 0:
print("You Are Out Of cash " + name + " Top Up ")
return balance
else:
print("Sorry You Dont Have Enough Money")
print("Hello " + name)
passwordAttempted = input("Please Enter Your Password: ")
if passwordAttempted == password:
print("Welcome " + name)
balance = playgame()
while input("You want to play again? Y/N").lower() == "y":
balance = playgame(balance)
else:
print ("Wrong Password " + name + " !")
Please note, that this code is not tested and may not work how you want.
Since balance is local to the function playgame() every time the function is called, the variable will be reset. You can fix this problem a couple of ways. You can make balance a global variable, or you can add a loop where the function doesn't return after one execution. The second example I gave would look something like this:
global balance
name = input ("Please Enter Your Name: ")
password = input ("Please Make A Password: ")
def playgame():
balance = 2000
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
while yesOrNo == "y":
howBigABet = int(input("How Much Would You like to bet?: "))
if howBigABet <= balance:
pickNumber = int(input("Please PicK A Number: "))
from random import randint
value = randint(0, 1)
print(value)
if pickNumber == value:
print(value)
balance = balance + howBigABet * 2
print("you won " + str(howBigABet * 2))
print(balance)
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
continue
else:
print ("Sorry Wrong Number")
balance = balance - howBigABet
print("your new balance is: " + str(balance))
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
continue
if balance <= 200:
print("You Are Low on Cash Top up?")
elif balance <= 0:
print("You Are Out Of cash " + name + " Top Up ")
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
continue
else:
print("Sorry You Dont Have Enough Money")
print("Hello " + name)
passwordAttempted = input("Please Enter Your Password: ")
if passwordAttempted == password:
print("Welcome " + name)
playgame()
else:
print ("Wrong Password " + name + " !")
The first thing playgame does is set your balance to 2000, so it's always going to be 2000 at the beginning of a game. This is happening because you restart a new game by calling playgame() from within playgame. This is called recursion. It's a powerful tool that has a lot of uses, but this is probably not the best use of it. Among other things, when a game ends, it's going to return to where it was in the previous game, and pick up executing the next statement after playgame(). (You don't have anything like that in your current code, but the moment you do, you'll get confused. In short, playgame() is not a simple "go back to the beginning" command.)
So one way to address this is to change the main structure of your function to a loop. After balance = 2000 add:
while True:
and indent the rest of the function under that statement.
Wherever you have playgame() within the playgame function, change it to continue. This will cause the program to go back to the beginning of the while loop.
Since balance = 2000 is not within the loop, it will be executed once and will not be re-executed for subsequent games.
Another way to solve the problem (keeping the recursion) is to move the initialization of balance outside the loop, say to right after you ask for the user's name and password. In the playgame function, replace balance = 2000 with global balance. This way, the variable is not local to the function and will retain its value from call to call.
Finally, you could make the game a class rather than a standalone function. This way, balance can be an attribute of the object rather than a local variable to your function, but still not a global. (Global variables are generally a bad idea, especially as your code gets more complex, because they make it difficult to keep track of every piece of the data the function uses to do its job.) This is probably the best way to do it long-term, but you'll need to learn a bit more about programming before you tackle that.
Elaborating on loops since you said you are new to python, you can initiate the balance variable outside the function, and in a loop, you can ask for user input and call the function. Based on the input, you can rerun the function or exit and display balance.
One way would be, to modify you if-else loop for yesOrNo and add an elif (say elif yesOrNo=='end'), then break the loop and display balance.

(Python 3 ATM Program) How do I update the Balance every time I withdraw and Deposit?

I'm creating python ATM for my project, and I need to Update the Balance every time I withdraw and Deposit. However, when I withdraw then check the balance, the balance does not update. Same thing when I withdraw or deposit. How do I update the Balance every time I withdraw and Deposit?
balance=1000
print(" Simple ATM Program ")
print("\n1)\tBalance\n2)\tWithdraw\n3)\tDeposit\n4)\tQuit\n")
def viewbalance():
print("Your Current Balance is: ₱", balance)
def withdrawbalance():
viewbalance()
withdraw = int(input("Enter Amount to Withdraw: "))
if withdraw < 1000:
withdrawal = balance - withdraw
print("Withdrawal Succeed")
print("Your Remaining Balance is: ₱" + str(withdrawal))
else:
print("Insufficient Balance")
print("Enter a Valid Balance")
return withdrawbalance()
def depositbalance():
viewbalance()
deposit = float(input("Enter Deposit Amount: ₱ "))
deposit = balance + deposit
print("Your New Balance is: ₱" + str(deposit))
while True:
Option = int(input("Select Option: "))
if Option == 1:
viewbalance()
elif Option == 2:
withdrawbalance()
elif Option == 3:
depositbalance()
elif Option == 4:
exit()
else:
print("Please Select Only the Options Above")
balance=1000
print(" ATM ")
print("\n1)\tBalance\n2)\tWithdraw\n3)\tDeposit\n4)\tQuit\n")
while True:
Option=int(input("Enter Option: "))
if Option==1:
print("Balance $ ",balance)
if Option==2:
print("Balance $ ",balance)
Withdraw=float(input("Enter Withdraw amount $ "))
if Withdraw>0 and Withdraw<=balance:
balance -= Withdraw
print("Foreward Balance $ ",balance)
elif Withdraw>balance:
print("No funs in account")
else:
print("None withdraw made")
if Option==3:
print("Balance $ ",balance)
Deposit=float(input("Enter deposit amount $ "))
if Deposit>0:
balance += Deposit
print("Forewardbalance $ ",balance)
else:
print("None deposit made")
if Option==4:
exit()
Replace the 'forewardbalance' variable with the variable 'balance'
or
Set the balance variable to foreward balance in your options.
balance=forewardbalance
Additional tip: In Option 2, make the elif condition (balance is greater than the withdrawal amount ) as the if condition.

Two of my functions don't work correctly, IDE doesn't show errors or crashes

The deposit function and the withdraw function doesn't work. After populating the accounts, I can select D or W menu options and input any number without causing the program to crash or causing an error. The program seems it is working correctly but when you check the balances using the S option, they are not updated.
Names=[]
accountnumbers=[]
balance=[]
def populatelist():
position=0
while(position<=2):
yourname= str(input("Please enter a name: "))
Names.append(yourname)
account = int( input("Please enter an account number: " ))
accountnumbers.append(account)
totalbalance = int( input("Please enter a balance: "))
balance.append(totalbalance)
position = position + 1
##################################### DEPOSIT FUCNTION
def deposit(accountnumber):
foundposition=-1
position=0
if (len(accountnumbers)>0):
while (position <=2):
if (accountnumber==accountnumbers[position]):
return position
position = position + 1
return foundposition
#################################### WITHDRAW FUNCTION
def withdraw(accountnumber):
foundposition=-1
position=0
if (len(accountnumbers)>0):
while (position <=2):
if (accountnumber==accountnumbers[position]):
return position
position = position + 1
return foundposition
def findingaccount(accountnumber):
foundposition=-1
position=0
if (len(accountnumbers)>0):
while (position <=2):
if (accountnumber==accountnumbers[position]):
return position
position = position + 1
return foundposition
def menuoptions():
print ("**** MENU OPTIONS ****")
print ("Type P to populate accounts")
print ( "Type S to search for account")
print ("Type E to exit")
print ("Type D to deposit Amount")
print ("Type W to withdraw Amount")
choice = str(input("Please enter your choice: "))
return choice
response=""
while response!= "E":
response = menuoptions()
if response=="P":
populatelist()
########################### Deposit OPTION
elif response=="D":
searchaccount = int(input("Please enter the account number to add deposit: "))
foundtheposition = deposit(searchaccount)
money = int(input("Please enter the amount to be deposited: "))
money + (balance[foundtheposition])
########################### WITHDRAW OPTION
elif response=="W":
searchaccount = int(input("Please enter the account number to withdraw: "))
thenumber = withdraw(searchaccount)
withdraw = int(input("how much for withdraw"))
withdraw - (balance[thenumber])
if (balance[thenumber]) < withdraw :
print("ERROR: Not enough balance")
elif response=="S":
searchaccount = int(input("Please enter the account number to search: "))
foundaposition = findingaccount(searchaccount)
if ( foundaposition == -1 ):
print ("The account number not found!")
else:
print ("Name is:" + str( Names[foundaposition]))
print (str(Names[foundaposition]) + " " + "account has the balance of :" +str(balance[foundaposition]))
elif response=="E":
print ("Thank you for using the program.")
print ("Bye")
exit
else:
print ("Invalid choice. Please try again!")
You have logic error.
Just change
money + (balance[foundtheposition])
to
balance[foundtheposition] = balance[foundtheposition] + money
or using short-hand operator like
balance[foundtheposition] += money
Same for
withdraw - (balance[thenumber])
Cheers ...
Your deposit scenario needs to add the amount into the selected account:
balance[thenumber] += money
Fair warning there are other errors in your program besides the accounts not updating.

Categories