The most common answer to the 4.3.10 Transaction CodeHS is:
"""
This program simulates a single transaction -
either a deposit or a withdrawal - at a bank.
"""
inital_value = 1000
Selection = input("Deposit or withdrawal: ")
if(Selection=="deposit"):
MoneyAdd=int(input("Enter Amount: "))
inital_value += MoneyAdd
print("Final balance: "+(str(inital_value)))
elif(Selection=="withdrawal"):
WithDrawMoney =int(input("Enter Amount: "))
inital_value -= WithDrawMoney
if(WithDrawMoney>inital_value): #CodeHS has a gltich where it only accepts this incorrect. WithDrawMoney Must be less than 0
print("You cannot have a negative balance!")
print("Final balance: "+(str(inital_value)))
else:
print("Invalid transaction.")
It is almost correct, but the withdrawal section has a logical error. The check for a negative balance should be done before updating the initial_value
.
Let’s correct this:
initial_value = 1000 # Corrected the spelling of 'initial_value'
selection = input("Deposit or withdrawal: ")
if selection.lower() == "deposit":
money_add = int(input("Enter Amount: "))
initial_value += money_add
print("Final balance: " + str(initial_value))
elif selection.lower() == "withdrawal":
withdraw_money = int(input("Enter Amount: "))
if withdraw_money > initial_value:
print("You cannot withdraw more than your current balance!")
else:
initial_value -= withdraw_money
print("Final balance: " + str(initial_value))
else:
print("Invalid transaction.")
Corrections and improvements:
- Spelling Correction: Corrected the variable name
inital_value
toinitial_value
. - Case Insensitivity: Added
.lower()
toselection
input to handle different cases (like “Deposit”, “deposit”, “DEPOSIT”). - Logical Error in Withdrawal: The balance check (
if withdraw_money > initial_value
) is now done before deducting the withdrawal amount. If the withdrawal amount is more than the current balance, it prints a warning message without updating the balance. - Reducing Variable Scope: Moved the variables
money_add
andwithdraw_money
inside their respective conditional blocks, as they are not needed outside those blocks.
This corrected code will now handle deposits and withdrawals correctly, ensuring that the account balance does not go negative.