I am doing a project for class and can't figure out where I am going wrong. The code works in sections, but when I run it all together it shuts down right after the first input.
I think I need to call functions somewhere - but how and where?
Below is all my code so far, with comments.
import sys
#account balance
account_balance = float(500.25)
##prints current account balance
def printbalance():
print('Your current balance: %2g'% account_balance)
#for deposits
def deposit():
#user inputs amount to deposit
deposit_amount = float(input())
#sum of current balance plus deposit
balance = account_balance + deposit_amount
# prints customer deposit amount and balance afterwards
print('Deposit was $%.2f, current balance is $%2g' %(deposit_amount,
balance))
#for withdrawals
def withdraw():
#user inputs amount to withdraw
withdraw_amount = float(input())
#message to display if user attempts to withdraw more than they have
if(withdraw_amount > account_balance):
print('$%.2f is greater than your account balance of $%.2f\n' %
(withdraw_amount, account_balance))
else:
#current balance minus withdrawal amount
balance = account_balance - withdraw_amount
# prints customer withdrawal amount and balance afterwards
print('Withdrawal amount was $%.2f, current balance is $%.2f' %
(withdraw_amount, balance))
#system prompt asking the user what they would like to do
userchoice = input ('What would you like to do? D for Deposit, W for
Withdraw, B for Balance\n')
if (userchoice == 'D'): #deposit
print('How much would you like to deposit today?')
deposit()
elif userchoice == 'W': #withdraw
print ('How much would you like to withdraw today?')
elif userchoice == 'B': #balance
printbalance()
else:
print('Thank you for banking with us.')
sys.exit()
This part should be as one userchoice = input ('What would you like to do? D for Deposit, W for Withdraw, B for Balance\n')
Not sure if you indented by accident, but python does not like that.
Also, advice for your code. Make it so user can either do uppercase or lowercase letters for input, also make sure it still grab input even if user put empty spaces after input string.
Your withdraw exit the program after entering the string character W.
Balance is not grabbing the correct Deposit.
Use for loops and condition to keep it looping and ask user when to exit.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
Is there any other way we can insert an if-else statement or a function that restricts withdrawal from account and sets the minimum amount the account should have specifically "5000" or else the loop will break or restricts withdrawal from user.
I recently did add an if-else statement in my simple atm ui that sets the maximum the user could withdraw "100k" and breaks if the user withdraws greater than the max amount.
Heres the code:
import time
print("Welcome to OtnisBank")
print("Please insert your card...")
time.sleep(5)
pwd = 1234
pin = int(input("Please enter your security pin: "))
bal = 737000
transaction_Num = 20221000114
while True:
if pin == pwd:
print("""
********************************************
1) Balance
2) Withdraw
3) Deposit
4) Cancel Transaction
********************************************
""")
try:
opt = int(input("Please choose your transaction "))
except:
print("Invalid input, input must be an integer.")
if opt == 1:
print(f"Your current balance is ₱{bal}.00")
if opt == 2:
print("Maximum of 100k per transaction")
withdraw = int(input("Please enter amount: "))
if withdraw > 100000:
print("Invalid amount, maximum of 100k per transaction.")
else:
bal = bal - withdraw
print(f"₱{withdraw}.00 is withdrawn from your account...")
print(f"Your updated balance is ₱{bal}.00")
if opt == 3:
deposit = int(input("How much money would you like to deposit?: "))
bal = bal + deposit
print(f"₱{deposit}.00 is deposited unto your account...")
print(f"Your updated balance is ₱{bal}.00")
if opt == 4:
print("Transaction success...")
print(f"Transaction number: {transaction_Num + 1}")
print(
"Thank you for choosing our bank. Invest in the red, it's in your best interest.")
break
else:
print("Please enter a valid pin and try again.")
break
Is there any other way we can insert a block of code that restricts account's minimum balance, it must have at least 5000 to be left in the account or else it will be deleted or something. By the way "bal" variable is global.
I'm not sure I understand 100% what you are trying to do, but with this code, you can make sure, that the customer must have 5000 left on the account after withdrawal:
if withdraw > 100000:
print("Invalid amount, maximum of 100k per transaction.")
elif (bal - withdraw) < 5000:
print("Invalid amount, You must have at least 5000 left on your account.")
else:
bal = bal - withdraw
print(f"₱{withdraw}.00 is withdrawn from your account...")
print(f"Your updated balance is ₱{bal}.00")
Hi I'm working on an assignment where I make a self-service program. I'm having trouble trying to incorporate a while loop while collecting user input. I want my code to collect an amount of money (entered by the user) and prompt the user on how much more they need to pay. Once the amount paid exceeds the amount due, I want to continue with the rest of my code. This is what I have so far but the loop stops after 2 inputs, even if the user has not paid enough.
elif paid < TotalCost:
due = TotalCost - paid
while due > 0:
print("You need to pay $",round(due,2)," more.")
morepaid=float(input("Enter the amount paid: $"))
if morepaid>TotalCost:
change= morepaid- TotalCost
print("Change due: $",round(change,2))
print(" ")
print("Thank you for visiting McDonald's")
elif due== 0:
print("Change due: $0.00")
print(" ")
print("Thank you for visiting McDonald's")
else:
due -= morepaid
You can simply subtract the amount paid from due, you don't need another variable totalpaid.
elif paid < totalCost:
due = totalCost - paid:
while due > 0:
print("You need to pay $",round(due,2)," more.")
morepaid=float(input("Enter the amount paid: $"))
due -= morepaid
# PHASE 1 (FILE I/O with One Customer)
# Initialization of Current Balance ** Current Balance is the same for all users for the sake of simplicity **
myMoney = open("current_balance.txt")
currentBalance = int(myMoney.readline())
# Creation of Bank Account and Notifying User(s) of Current Balance
class Bank_Account:
def __init__(self):
self.balance= currentBalance
print("Welcome to Your Bank Account System!")
# If statements for the different options
def options(self):
ch = int(input("1. Withdraw Money From Your Account\n2. Deposit Money From Your Account\n3. Create an Account\nEnter a Choice: "))
if ch == 1:
s.withdraw
if ch == 2:
s.deposit
if ch == 3:
s.create
# Function to Deposit Money
def deposit(self):
amount=float(input("Enter the amount you want to deposit: "))
self.balance += amount
print("Amount Deposited: ",amount)
# Function to Withdraw Money
def withdraw(self):
amount = float(input("Enter the amount you want to withdraw: "))
if self.balance>=amount:
self.balance-=amount
print("You withdrew: ",amount)
else:
print("Insufficient balance ")
# Function to Create an Account
def create(self):
user = str(input("Enter your username:"))
pin = int(input("Enter your pin number:" ))
print("test")
def display(self):
print("Net Available Balance=",self.balance)
# Creating an object of class
s = Bank_Account()
# Calling functions with that class
s.options()
s.withdraw()
s.deposit()
s.create()
s.display()
# PHASE 2 (With Database)
** When I choose option 3 to create an account it's supposed to ask the user for a username and pin to create an account but instead it goes straight to withdraw money. I'm not sure why this is happening. I'm trying to make a bank account management system as a project.
To be clearer, I've pasted the full code. My question is on the "withdrawal()" function. The account.name variable in the second print statement shows only the first account name on the list despite the loop being on a different account name
def validation(accounts):
pin = int(input("Enter 4 digits pin: "))
for account in accounts:
if pin == account.pin and len(str(pin)) == 4:
print("\nWelcome! {}, your account balance is ${}".format(account.name, account.balance))
return withdrawal(accounts)
print("\nInvalid pin.\n")
return try_again(accounts)
def withdrawal(accounts):
amount = int(input("\nEnter amount to withdraw: "))
for account in accounts:
if account.balance > amount:
account.balance -= amount
print("\nTransaction successful, your new balance is ${}".format(account.balance))
new = input("\nNew transaction? YES/NO?: ")
if new.lower() == "yes":
return withdrawal(accounts)
print("\nTake your card {}. Thank you for banking with us.".format(account.name))
break
else:
print("\nTransaction failed due to insufficient funds.")
def try_again(accounts):
re_enter = input("Enter YES to try again or NO to exit: ")
if re_enter.lower() == "yes":
return "\n" + validation(accounts)
elif re_enter.lower() == "no":
print("\nGoodbye. Take your card.")
else:
print("\nInvalid input. Take your card.")
class Account:
def __init__(self, name, pin, balance):
self.name = name
self.pin = pin
self.balance = balance
accounts = [Account("Bryan Somto", 4289, 300000), Account("Dubem Vic", 3329, 250000), Account("Munz Gee", 2200, 220000)]
validation(accounts)
Summary
Simply put, it's because every time the withdrawal function is called, it iterates through all the accounts, and does the transaction with the first account that has a high enough balance. As "Bryan Somto" is the first account, the transaction always happens with that account. Modify the withdrawal function to only take in the specific account to do the transaction with.
Explanation
When you call the withdrawal function, you should instead only pass the specific account where the user is doing the transaction. So, instead of calling withdrawal(accounts), call withdrawal(account). Then only that specific account is passed to the function.
def withdrawal(account):
amount = int(input("\nEnter amount to withdraw: "))
if account.balance > amount:
account.balance -= amount
print("\nTransaction successful, your new balance is ${}".format(account.balance))
# New transaction
new = input("\nNew transaction? YES/NO?: ")
if new.lower() == "yes":
return withdrawal(account)
print("\nTake your card {}. Thank you for banking with us.".format(account.name))
else:
print("\nTransaction failed due to insufficient funds.")
Here, the withdrawal function only deals with the specific account.
It would be best if you also modify your validation function. Because currently, it won't work if multiple people have the same PIN.
It should first take in the account holder's name, and then the PIN. Then it should check if the two match up.
So like this:
def validation(accounts):
name = input("Enter your name: ")
for account in accounts:
# Checking account name
if account.name == name:
pin = int(input("Enter 4 digits PIN: "))
# Checking PIN length
if len(str(pin)) != 4:
print("\nInvalid PIN.\n")
return try_again(accounts)
# Checking PIN
if account.pin == pin:
print("\nWelcome! {}, your account balance is ${}".format(account.name, account.balance))
return withdrawal(account)
else:
print("\nThe PIN is incorrect")
return try_again(accounts)
else:
print("\nThere is no account with that name.")
return try_again(accounts)
Here it also only checks the length of the pin once. In the original code, it checks the length every time, and that's unnecessary.
In the first if block of the try_again function, it would be better if you change return "\n" + validation(accounts) to return validation(accounts).
You don't need that newline character, and it could cause bugs down the road.
Aside
Regarding checking the account name:
The standard practice is to use an account number/ID that will definitely be unique, then even if two people have the same name, it will still work. It's also better because it's generally easier to type in an account number instead of typing in a long name. In this one, if two people have the same name, it will go with the one that is first in the accounts list, and will never get to the second one.
Creating a small, simple ATM-like software. I've made functions for the various actions available. However in the output my global variable 'balance' isn't being updated. Below is the relevant snippet of code.
After some testing I realized that the value is understood to be changed within the function as when I deposit a value, I'm able to withdraw greater than the initial balance. So that means the variable is being updated for the functions at least.
global menu
balance = float(input("Please enter your current balance: "))
menu = "Current balance is: {}\n Press 1 to withdraw\n Press 2 to deposit\n Press 3 to exit".format(balance)
def display():
global choice
global balance
print(menu)
choice = input("Please select a number: ")
return balance
def deposit():
global balance
global choice
amount_dep = float(input("Please enter the amount you'd like to deposit: "))
balance += amount_dep
return "Your current balance is{}".format(balance)
def withdraw():
global balance
global choice
amount_with = float(input("Please enter the amount you'd like to withdraw: "))
if amount_with > balance:
print("Sorry, but your balance is less than the amount you'd like to withdraw.")
else:
balance -= amount_with
return "Your current balance is{}".format(balance)
while finished == False:
display()
global choice
if choice == '1':
withdraw()
elif choice == '2':
deposit()
elif choice == '3':
finished = True
print("Thank you for using our service.")
else:
print("You entered an invalid number, please retry")
So all the output is regular, except the value of balance.
When you define the variable menu at the top of the code, you define it with the initial balance. When you print the menu after a deposit or withdrawl, the display routine is still printing the menu defined with the initial balance.
You may be working on an assignment where you are supposed to use global variables, but this doesn't seem like a great use case. Your withdrawl function returns a string stating your current balance, but you don't use it. You could as easily call the withdrawl function with balance = withdraw(balance) and treat the balance as an argument and a return. Anyway, keep working it and keep learning!