gpt4 book ai didi

python - 在字典 Python 中传递值的函数

转载 作者:行者123 更新时间:2023-11-28 19:28:31 25 4
gpt4 key购买 nike

我是 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')

最佳答案

这里有几件事,首先是最简单的,总是以大写字母开始一个类,这不是必需的,但这是一个很好的做法:

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')

关于python - 在字典 Python 中传递值的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58567496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com