在字典Python中传输值的函数

时间:2019-10-26 02:07:45

标签: python

我是Python的新手,正在尝试为分配函数创建一个功能,该功能会将资金从支票转入储蓄帐户。我们获得了以下初始代码:

class portfolio:

    def __init__(self):
        self.checking = {}
        self.saving = {}
        self.credit = {}
        self.stock = {}

然后从此代码的开头开始进行转账功能:

def invest_in_savings_account(self, account_id_savings, amount, account_id_checking):

我尝试了很多代码,但是没有一个可以通过测试用例。有人可以向我解释为什么这行不通吗?

def invest_in_savings_account(self, account_id_savings, amount, account_id_checking):
    try:
       self.checking[account_id_checking] -= amount
       self.saving[account_id_savings] += amount
    except:
          return None

如果帐户ID不存在或支票帐户中没有资金,该功能将不执行任何操作。 任何建议将不胜感激!我整天都在工作,但无法解决它。

这是它必须通过的测试用例:

myportfolio.invest_in_savings_account('discover_saving_3785', 1000, 'discover_7732')
if (myportfolio.saving == {'chase_saving_4444': 0, 'discover_saving_3785':1000}) and (myportfolio.checking == {'chase_6688': 100, 'discover_7732':5500}):
    print('Pass')
else:
    print('Fail')

1 个答案:

答案 0 :(得分:-1)

这里发生了一些事情,最简单的是首先,总是以大写字母开头的课,这不是必须的,但这是一个好习惯:

def class Portfolio:

在阅读您的评论后,您似乎需要它而帐户中没有钱。您可以编写代码,但无法对其进行测试,因此,实际上您需要使用创建帐户以及添加/删除资金的功能。如果您还没有创建任何帐户,那么您的词典将总是空着。如果您不花钱,那么该功能将永远不会做任何事情,我对您将如何移动不存在的东西感到困惑。

尝试这样的事情:

def create_checking_account(self,account_id):
    self.checking[account_id] = None

def add_funds_checking(self,account_id,amount):
    self.checking[account_id] += amount

def invest_in_savings(self, account_id_savings, amount, account_id_checking):

    if self.checking[account_id_checking] >= amount:
        self.checking[account_id_checking] -= amount
        self.savings[account_id_savings] += amount
    else:
        print('error')