1 回答

TA貢獻1853條經驗 獲得超18個贊
概括
簡單地說,這是因為每次withdrawal調用該函數時,它都會迭代所有帳戶,并與第一個具有足夠高余額的帳戶進行交易。由于“Bryan Somto”是第一個帳戶,因此交易始終通過該帳戶進行。修改該withdrawal函數以僅接受用于進行交易的特定帳戶。
解釋
當您調用該withdrawal函數時,您應該只傳遞用戶正在進行交易的特定帳戶。因此,不要調用 ,而是withdrawal(accounts)調用withdrawal(account)。然后僅將該特定帳戶傳遞給該函數。
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.")
這里,該withdrawal函數僅處理特定帳戶。
如果您也修改您的功能,那就最好了validation。因為目前,如果多個人擁有相同的 PIN,則無法正常工作。它應首先輸入帳戶持有人的姓名,然后輸入 PIN。然后它應該檢查兩者是否匹配。
像這樣:
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)
這里它也只檢查一次引腳的長度。在原始代碼中,它每次都會檢查長度,這是不必要的。
if在函數的第一塊中,如果改為try_again會更好。您不需要換行符,它可能會導致錯誤。return "\n" + validation(accounts)return validation(accounts)
在旁邊
關于檢查賬戶名:
標準做法是使用一個絕對唯一的帳號/ID,那么即使兩個人同名,它仍然有效。它也更好,因為通常輸入帳號比輸入長名稱更容易。在這個例子中,如果兩個人有相同的名字,它將選擇列表中的第一個accounts,而永遠不會到達第二個。
添加回答
舉報