簡體   English   中英

Function 在字典 Python 中傳輸值

[英]Function to transfer values in dictionary Python

我是 Python 的新手,並試圖制作 function 的任務,將錢從支票轉移到儲蓄賬戶。 我們得到了這個初始代碼:

class portfolio:

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

然后開始這段代碼讓function轉錢:

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 不存在或者支票賬戶中沒有資金,則 function 什么也不做。 任何建議將不勝感激。 我已經為此工作了一整天,但無法解決它。

這是它必須通過的測試用例:

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

這里發生了一些事情,最簡單的首先,始終以大寫字母開頭 class,這不是必需的,但這是一種很好的做法:

def class Portfolio:

閱讀您的評論后,您似乎需要在賬戶中沒有資金的情況下工作。 您可以編寫代碼,但無法對其進行測試,因此您確實需要創建函數來創建帳戶和添加/刪除資金。 如果您還沒有創建任何帳戶,您的字典將永遠是空的。 如果您不向它們投入資金,那么 function 將永遠不會做任何事情,我很困惑您將如何移動 go 來移動不存在的東西。

嘗試這樣的事情:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM