I'm making a ATM-type program in which I have to ask the user if they want to deposit, withdraw, or check their balance in their savings or checking account, but only if the pin they enter is 1234. I've been instructed to use global variables and initialize savings and checking as 0. All of my functions are working properly, but when the program loops again the savings and checking balances are still 0, even when the user has just deposited money into either account. I'm not sure which part of my code is messing this up, but any help is greatly appreciated.
#Create global variables
Checking = 0
Saving = 0
def main():
pin_number = input("Please enter your pin number ")
stop = False
while not is_authorized(pin_number) and stop!= True:
if pin_number == "0":
stop = True
if pin_number == "1234":
stop = False
if stop != True:
while True:
choice = display_menu()
if choice == 1:
deposit()
elif choice == 2:
withdraw()
elif choice == 3:
check_balance()
def is_authorized (pin_number):
if pin_number == "1234":
return True
else:
return False
def display_menu():
print('1) Deposit')
print('2) Withdraw')
print('3) Check amount')
choice = int(input("Please enter the number of your choice: "))
return choice
def deposit():
depositing=str(input("Would you like to deposit into your savings
or checking? "))
if depositing == "savings":
depo = float(input("How much would you like to deposit? "))
new_savings = Saving + depo
print ("Your new balance is" +str (new_savings))
elif depositing == "checkings":
depo = input(int("How much would you like to deposit? "))
new_checking = Checking + depo
print ("Your new balance is" +str (new_checking))
def withdraw():
print ("Your savings account balance is " +str (Saving))
print ("Your checkings account balance is " +str (Checking))
withdrawing=str(input("Would you like to withdraw from your checking or savings? "))
if withdrawing == "checking":
withdraw = int(input("How much would you like to withdraw? "))
checking2= Checking - withdraw
print ("Your new balance is" +str (checking2))
elif withdrawing == "savings":
withdraw = int(input("How much would you like to withdraw? "))
savings2= Saving - withdraw
print ("Your new balance is" +str (savings2))
def check_balance():
checkbalance= input("Would you like to check your savings or checking? ")
if checkbalance == "savings":
print (Saving)
elif checkbalance == "checking":
print ("Your balance is $" +str (Checking))
main()
In order to modify values Saving and Checking in your functions you have to declare them global inside the function, not the use of global is not the most optimal, as far as I know, but it seems that is your task at hand. Your while loop can be simplified, by using while True and break. Along the way I found a few small things I touched up, I would also consider changing Saving to Savings since that is the keyword you are accepting as a response, makes things easier for you.
Checking = 0
Saving = 0
def main():
while True:
pin_number = input("Please enter your pin number ")
while pin_number not in ('0','1234'):
pin_number = input("Please enter your pin number ")
if pin_number == "0":
break
elif pin_number == "1234":
choice = display_menu()
if choice == 1:
deposit()
elif choice == 2:
withdraw()
elif choice == 3:
check_balance()
def is_authorized (pin_number):
if pin_number == "1234":
return True
else:
return False
def display_menu():
print('1) Deposit')
print('2) Withdraw')
print('3) Check amount')
choice = int(input("Please enter the number of your choice: "))
return choice
def deposit():
global Checking, Saving
depositing=str(input("Would you like to deposit into your savings or checking? "))
if depositing == "savings":
depo = float(input("How much would you like to deposit? "))
Saving += depo # use += here
print ("Your new balance is " +str (Saving))
elif depositing == "checking": # changed to checking
depo = int(input("How much would you like to deposit? "))
Checking += depo
print ("Your new balance is " +str (Checking))
def withdraw():
global Checking, Saving
print ("Your savings account balance is " +str (Saving))
print ("Your checkings account balance is " +str (Checking))
withdrawing=str(input("Would you like to withdraw from your checking or savings? "))
if withdrawing == "checking":
withdraw = int(input("How much would you like to withdraw? "))
Checking -= withdraw
print ("Your new balance is " +str (Checking))
elif withdrawing == "savings":
withdraw = int(input("How much would you like to withdraw? "))
Saving -= withdraw
print ("Your new balance is " +str (Saving))
def check_balance():
global Checking, Saving
checkbalance= input("Would you like to check your savings or checking? ")
if checkbalance == "savings":
print (Saving)
elif checkbalance == "checking":
print ("Your balance is $" +str (Checking))
main()
Related
I'm practicing with a simple roulette program. At this moment, I have a problem with balance input(), if I put it outside the function, the function betting() doesn't recognize it. But, if I put it inside, the function, the program asks me again to input the amount of money and it overwrites the amount of money after the bet.
How to avoid that, so the program asks me only once for input? This is my code:
import random
def betting():
balance = float(input("How much money do you have? $"))
your_number = int(input("Choose the number between 0 and 36, including these: "))
if your_number < 0 or your_number > 36:
print("Wrong input, try again!")
betting()
else:
bet = float(input("Place your bet: "))
while balance > 0:
if bet > balance:
print("You don't have enough money! Place your bet again!")
betting()
else:
number = random.randint(0,36)
print(f"Your number is {your_number} and roulette's number is {number}.")
if number == your_number:
balance = balance + bet*37
print(f"You won! Now you have ${balance}!")
else:
balance = balance - bet
print(f"You lost! Now you have ${balance}!")
betting()
else:
print("You don't have more money! Goodbye!")
quit()
def choice():
choice = str(input("Y/N "))
if choice.lower() == "y":
betting()
elif choice.lower() == "n":
print("Goodbye!")
quit()
else:
print("Wrong input, try again!")
choice()
print("Welcome to the Grand Casino! Do you want to play roulette?")
choice()
Pass the balance as a function parameter to betting(). Then ask once in the choice() function
import random
def betting(balance):
your_number = int(input("Choose the number between 0 and 36, including these: "))
if your_number < 0 or your_number > 36:
print("Wrong input, try again!")
return your_number
else:
bet = float(input("Place your bet: "))
while balance > 0:
if bet > balance:
print("You don't have enough money! Place your bet again!")
betting(balance)
else:
number = random.randint(0,36)
print(f"Your number is {your_number} and roulette's number is {number}.")
if number == your_number:
balance = balance + bet*37
print(f"You won! Now you have ${balance}!")
else:
balance = balance - bet
print(f"You lost! Now you have ${balance}!")
betting(balance)
else:
print("You don't have more money! Goodbye!")
quit()
def choice():
choice = str(input("Y/N "))
if choice.lower() == "y":
balance = float(input("How much money do you have? $"))
betting(balance)
elif choice.lower() == "n":
print("Goodbye!")
quit()
else:
print("Wrong input, try again!")
choice()
print("Welcome to the Grand Casino! Do you want to play roulette?")
choice()
You can ask for both at the same time and split the given string:
inp = input("State how much money you have and a number between 0 and 36 inclusive, separated by space: ")
bal, num = inp.split()
Python allocate a variable in the closest namespace.
This mean that balance is allocated in 'betting' namespace and will not be known outside 'betting'.
What you need is a global variable.
'global' mean that the variable must be allocated in the embracing namespace.
def betting():
global balance
print( balance)
def choice():
global balance
sel = input( ...)
if sel.lower() == 'y':
balance = int( input(">"))
betting()
choice()
Please note that you used 'choice' for 2 purposes. It's a function but it is also a variable. While it is possible, it is considered a bad habit.
Trying to create a simple transaction simulation just for practice using if statements, but when input is requested it defaults to the same if and doesn't change even when string literal variables are set in place.
I've tired moving things around, but everytime I run the code and it prompts me with Type "Deposit or "Withdraw" it will skip over proceed1 variable, and default to the amount1 variable input by prompting the user to "how much would you like to deposit."
import time
checking = 0
savings = 0
proceed1 = "Checking" or "checking"
proceed2 = "Savings" or "savings"
deposit = "Deposit" or "deposit"
withdraw = "Withdraw" or "withdraw"
time.sleep(1)
print("Thank you for choosing the Bank of Kegan")
time.sleep(1)
choice = str(input("Type \"Deposit\" or \"Withdraw\" \n "))
if choice == deposit:
print("Deposit Transaction Initiated: Checking ")
time.sleep(.5)
print("Please choose an account you would like to Deposit into. ")
account_choice = str(input("Type \"Checking\" or \"Savings\" \n "))
if account_choice == proceed1:
print("Checking Account Loading... \n")
time.sleep(2)
print("Checking: $", checking, "\n")
time.sleep(2)
amount1 = int(input("Please type how much you'd like to deposit. \n "))
time.sleep(.5)
print("$", amount1, "Transaction Pending...")
time.sleep(2)
checking = (checking + amount1)
print("Your new balance is: ")
print("$", checking)
exit()
elif account_choice == proceed2:
print("Savings Account Loading... ")
time.sleep(2)
print("Savings: $", savings)
time.sleep(2)
amount2 = int(input("Please type how much you'd like to deposit. \n "))
time.sleep(.5)
print("$", amount2, "Transaction Pending... ")
time.sleep(2)
savings = (savings + amount2)
print("Your new balance is: ")
print("$", savings)
exit()
else:
print("Please choose a valid argument ")
elif choice == withdraw:
print("Withdraw Transaction Initiated: Checking ")
print("Type what account you would like to withdraw from. ")
choice2 = str(input("Checking or Savings"))
if choice2 == proceed1:
print("Withdraw Transaction Initiated: Checking ")
print("Checking Account Loading... ")
time.sleep(2)
print("Checking \n Balance: ", checking)
withdraw1 = int(input("Type how much you would like to withdraw. "))
print("$", withdraw1, "withdraw transaction pending... ")
time.sleep(2)
if checking == 0:
print("You broke broke, make some money and come back later.")
else:
checking = withdraw1 - checking
print("your new balance is: $", checking)
elif choice2 == proceed2:
time.sleep(.5)
print("Savings Account Loading... ")
time.sleep(2)
print("Savings \n Balance: ", savings)
withdraw2 = int(input("Type how much you would like to withdraw. "))
print("$", withdraw2, "withdraw transaction pending... ")
time.sleep(2)
if savings == 0:
print("You broke broke, make some money and come back later.")
else:
savings = withdraw2 - savings
print("your new balance is: $", savings)
else:
print("Please choose a valid argument.")
I am trying to create an ATM that asks for a user name to log in and then for each user have three separate accounts to pick from. Within each of those accounts allow them to deposit, withdraw, and view balance. My problem is I am not very good with lists and I believe that is what is needed. I can not get the code to log in as a new user once I have already gone threw the code. example: I create a user Bob and log in and deposit money. Then I log out of Bob and want to create a new user Tim. when I create Tim it wont let me log it. It will keep giving me the same menu every time I put in Tim.
I believe I need to create a list of users, then a list for each user and I do not understand how to do so. Seeing from my code I just use set values for the funds in each account. Could this be a problem with why the main log in wont allow me to use another user?
user_list = []
data_list = []
index = -1
user_input = 0
user_account = 0
credit_input = 0
checking_input = 0
saving_input = 0
while user_input != 3:
print("1: Login\n2: New User\n3: Exit")
user_input = int(input("Please pick an option: "))
if user_input == 1:
username = input("Login: ")
while username not in user_list:
username = input("No user, try again: ")
index = user_list.index(username)
while user_account != 4:
print("Accounts:\n\n1: Credit\n2: Checking\n3: Savings\n4:Exit ")
user_account = int(input("Please pick an option: "))
if user_account == 1:
credit_funds = 0
while credit_input != 4:
print("1: Deposit")
print("2: Withdraw")
print("3: Credit Account Balance")
print("4: Exit")
credit_input = int(input("Pick an option: "))
if credit_input == 1:
number = int(input("Deposit amount: "))
credit_funds += number
print("Deposit of $", number)
elif credit_input == 2:
number = int(input("Withdraw amount: "))
while number > credit_funds:
print("\nInsufficient Funds")
break
else:
credit_funds -= number
print("\nSuccessful Withdraw of $", number)
elif credit_input == 3:
print("Avalable balance: $", credit_funds)
elif user_account == 2:
checking_funds = 0
while checking_input != 4:
print("1: Deposit")
print("2: Withdraw")
print("3: Checking Account Balance")
print("4: Exit")
checking_input = int(input("Pick an option: "))
if checking_input == 1:
amount = int(input("Deposit amount: "))
checking_funds += amount
print("Deposit of $", amount)
elif checking_input == 2:
amount = int(input("Withdraw amount: "))
while amount > checking_funds:
print("\nInsufficient Funds")
break
else:
checking_funds -= amount
print("\nSuccessful Withdraw of $", amount)
elif checking_input == 3:
print("Avalable balance: $", checking_funds)
elif user_account == 3:
saving_funds = 0
while saving_input != 4:
print("1: Deposit")
print("2: Withdraw")
print("3: Saving Account Balance")
print("4: Exit")
saving_input = int(input("Pick an option: "))
if saving_input == 1:
number3 = int(input("Deposit amount: "))
saving_funds += number3
print("Deposit of $", number3)
elif saving_input == 2:
number3 = int(input("Withdraw amount: "))
while number3 > saving_funds:
print("\nInsufficient Funds")
break
else:
saving_funds -= number3
print("\nSuccessful Withdraw of $", number3)
elif saving_input == 3:
print("Avalable balance: $", saving_funds)
elif user_input == 2:
username = input("Please pick a username: ")
while username in user_list:
username = input("Pick another please: ")
user_list.append(username)
When the user 'logs out' (presses 4 when logged in) you set user_account to 4 (an exit condition). It is never unset after that. Therefore when another user tries to login, the program tests user_account != 4, fails that test, and never enters the while loop (while user_account != 4). I suspect the same will happen for all other exit conditions.
I suggest resetting the value of any inputs to 0 after taking the appropriate action. Alternatively, use while True: and explicitly break when an exit condition is reached.
For example:
while True:
print("1: Login\n2: New User\n3: Exit")
user_input = int(input("Please pick an option: "))
if user_input == 1:
print("Option 1 selected")
# DO SOMETHING
elif user_input == 2:
print("Option 2 selected")
# DO SOMETHING
elif user_input == 3:
break
users={};stop='r'
def login(name,users):
if name in users.keys():
return True
return False
def create():
name=input('please write your name')
users[name]=0
def main(users):
print('Welcome to my ATM\n')
buff=input('SELECT one of the following:\nC)create account\nL)login')
if(buff=='C' or buff=='c'):
create()
elif(buff=='L' or buff=='l'):
name=input('name: ')
buff2=login(name,users)
if(buff2==False):
print('your name is not in account list')
elif(buff2==True):
buff=input('SELECT:\nA)cash report\nD)delete account')
if(buff=='A' or buff=='a'):
print(users[name])
elif(buff=='D' or buff=='d'):
k=users.pop(name)
print('finished! ')
while(stop=='r'):
buff3=input("press 's' to stop ATM otherwise press enter to continue ...")
if(buff3=='s'):
break
main(users)
I wish this works.
I'm writing an ATM program for a class project, and we're not allowed to use global variables. I used only local variables in my program, but it doesn't work.
def welcome():
print("Welcome to the ATM program!\nThis program allows you to deposit, withdraw, or view your balance!")
def menu():
print("1...Deposit\n2...Withdraw\n3...View Balance")
userChoice = int(input("Please enter your choice now: "))
if userChoice == 1:
def deposit(balance):
deposit = float(input("Please enter the amount you would like to deposit: "))
balance = balance + deposit
elif userChoice == 2:
def withdraw(balance):
withdraw = float(input("Please enter the amount you would like to withdraw: "))
balance = balance + withdraw
else:
def balance(balance):
print("Your balance is", balance)
deposit()
withdraw()
balance()
welcome()
menu()
When I run it, it just ends after I input a choice from the menu without any error messages.
There's no reason to define functions here - just execute that code in the if statements, instead:
def menu(balance):
print("1...Deposit\n2...Withdraw\n3...View Balance")
userChoice = int(input("Please enter your choice now: "))
if userChoice == 1:
deposit = float(input("Please enter the amount you would like to deposit: "))
balance = balance + deposit
elif userChoice == 2:
withdraw = float(input("Please enter the amount you would like to withdraw: "))
balance = balance + withdraw
else:
print("Your balance is", balance)
return balance
...
balance = 0
balance = menu(balance)
The reason nothing is happening is because, with the way your code is now, you're defining the functions but not calling them. Look at your indentation - the calls to withdraw(), deposit(), and balance() are only executed inside the else block. And without any arguments, to boot, which would cause an error if they were executed.
I'm a beginner in Python programming, therefore I'm following a course where we have to submit assignments every week.
The current assignment is to write a program where the user can Open, and Close and account, can Deposit and Withdraw money, and List the accounts (i.e. view all accounts and balance according to specific account).
My main problem is that the balance (which starts at 0) is the same for every account, while every account should have its own balance!
I came this far:
# -*- coding: utf-8 -*-
def print_menu():
print "1. List Account(s)"
print "2. Open an Account"
print "3. Close an Account"
print "4. Withdraw money"
print "5. Deposit Money"
print "6. Quit"
print
accounts = {}
menu_choice = 0
print_menu()
#balance = {}
balance = 0
while True:
menu_choice = int(input("Type in a number (1-6): "))
print
if menu_choice == 1:
print "Accounts"
for x in accounts.keys():
print "Accountnumber:", x, "with balance €", balance
print
elif menu_choice == 2:
print "Enter a new Accountnumber"
number = input("New accountnumber: ")
#phone = input("Number: ")
accounts[number]=balance
print "Accountnumber", number, "opened."
elif menu_choice == 3:
print "Close an Accountnumber"
number = input("Accountnumber: ")
if number in accounts:
#accounts[number]=balance
del accounts[number]
print "Accountnumber", number, "is closed."
else:
print "Accountnumber", number, "was not found"
#elif menu_choice == 4:
#print("Lookup Number")
#name = input("Name: ")
#if name in numbers:
# print("The number is", numbers[name])
#else:
# print(name, "was not found")
elif menu_choice == 4:
print "Withdraw money from Account."
number = input("Accoutnnumber: ")
if number in accounts:
withdraw = float(input("How much money would you like to withdraw? > "))
if withdraw < balance:
#accounts[number]=balance
numbers[balance] -= withdraw
#balance vann number 444 bijv. !!
print "Your new balance is €", balance
else:
print "There are no sufficient funds on this accountnumber"
elif menu_choice == 5:
print "Deposit money onto Account."
number = input("Accountnumber: ")
if number in accounts:
deposit = float(input("How much money would you like to deposit? > "))
#accounts[number]=balance
balance += deposit
#balance vannn number 444 bijv. !!
print "Your new balance is €", balance
else:
print "That accountnumber does not exist."
elif menu_choice == 6:
print "Quit."
break
else:
print "Please enter a number between 1 and 6."
print
print_menu()
# Ook nog ff instellen dat wanneer input geen iets anders is,
# dan gewoon netjes afluisten, geen rare foutcodes !!
The problem is that you are using "balance" in a wrong way. It's far better if you use accounts like a dictionary, where you have "accounts numbers" and "balance".
This way if you have something like:
accounts = {1:100, 2:1500, 3:0}
that means that the person with account numbered 1 has 100$, the second person with acc number 2 has 1500 and so on.
For example in choice 4 you are doing this:
elif menu_choice == 4:
print "Withdraw money from Account."
number = input("Accoutnnumber: ")
if number in accounts:
withdraw = float(input("How much money would you like to withdraw? > "))
if withdraw < balance:
#accounts[number]=balance
numbers[balance] -= withdraw
#balance vann number 444 bijv. !!
print "Your new balance is €", balance
else:
print "There are no sufficient funds on this accountnumber"
But this is better:
elif menu_choice == 4:
print "Withdraw money from Account."
number = input("Accoutnnumber: ")
if number in accounts:
withdraw = float(input("How much money would you like to withdraw? > "))
balance = accounts[number]
if withdraw < balance:
accounts[number] -=withdraw
print "Your new balance is €", accounts[number]
else:
print "There are no sufficient funds on this accountnumber"
I hope this help with your homework.