微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

打印清单,仅显示列表中的第一个帐户名

如何解决打印清单,仅显示列表中的第一个帐户名

为清楚起见,我粘贴了完整的代码。我的问题是关于“ withdrawal()”函数的。尽管循环位于另一个帐户名上,但第二个打印语句中的account.name变量仅显示列表中的第一个帐户名

user@remoteHostname $ gdbserver :9091 ./myapplication arguments to my program

解决方法

摘要

简而言之,这是因为每次调用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列表中的第一个一起出现,并且永远不会到达第二个。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。