How to permanently change a variable in Python? - 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.

Related

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.

why can't i enter if condition 3 and 4. 1 and 2 are working fine for this sample banking code

please can anyone check my code and correct me why I am unable to enter if statement when I was given option input==3 and option input==4.
import sys,os,math
Account_balance= int(25000)
print('*** WELCOME TO SBI BANK NAKKALAGUTTA ***')
givenpin=input('Enter The 4 Digit Pin Number ')
if givenpin =='0351':enter code here
print('welcome MR.Anudeep RAO')
else:
print('unauthorized access try again')
sys.exit()
print('your A/C number is: 10987xxxxxx')
print("### choose an option below ###")
print("""
1) Balance
2) Withdraw
3) Deposit
4) Quit
""")
option = int(input("Enter option:"))
if option == 1:
print('your Account balance is' +' '+ str(int(Account_balance)) +'Rs/-')
elif option == 2:
input_to_Withdraw = int(input("enter amount to withdraw "))
if input_to_Withdraw > 25000:
print("Insufficient Funds in Your A/C")
elif input_to_Withdraw < 25000:
present_balance = (Account_balance - input_to_Withdraw)
print('collect cash and available balance is ' + str(int(present_balance)))
if option == 3:
Input_to_Deposit = int(input("enter amount to deposit into A/C "))
print('deposited balance is:')
print(Account_balance +Input_to_Deposit)
if option == 4:
print('Transaction complete leave bank safely Bye:')
The if option == 3: and if option == 4: cases are deep inside the elif option == 2: case. Since you don't reset the value of option anywhere, I assume this is a mistake.
Fix the indentation of these two cases so your code has a chance to follow these paths. They should be at the same indentation level as elif option == 2:.

How to make a Pin pritection thing for an ATM in python 2.7

Okay so I have done most of the work but my pin code isn't working properly. You can enter a code but I want it to be you can only enter e.g 1234 to get in as so far you can but any number and get it, I tried using an else statement but I cant get it to work, any help? Also does anyone know how I could write this stuff to a file, for example, your write your name e.g joe, it finds your balance etc maybe I could do this with the pin too? not sure need some help, thanks
balance = float(0)
userInput = None
pin = int(input('Please enter the 4 digit pin on your card:'))
if pin == (1234):
print('Correct pin!')
print "Hello, welcome to the ATM"
while userInput != "4":
userInput = raw_input("\n what would you like to do?\n\n (1)Check balance\n (2)Insert funds\n" +
" (3)Withdraw funds\n (4)Exit the ATM\n" )
if userInput == "1":
print "your balance is", "£" , balance
elif userInput == "2":
funds = float(raw_input("Enter how much money you want to add"))
balance = balance + funds
elif userInput == "3":
withdraw = float(raw_input("Enter how much money you want to withdraw..."))
balance = balance - withdraw
elif userInput == "4":
print "Thanks for using the ATM!"

Python ATM Else and Elif Errors

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()

Categories