簡體   English   中英

在 Python 的 while 循環中調用 function 及其先前的返回值作為參數

[英]Calling a function with its previous return value as an argument in a while loop in Python

我需要繼續調用以下 function 及其先前的返回值作為 while 循環中的參數:

def announce_lead_changes(last_leader=None):
    """Return a commentary function that announces lead changes.

    >>> f0 = announce_lead_changes()
    >>> f1 = f0(5, 0)
    Player 0 takes the lead by 5
    >>> f2 = f1(5, 12)
    Player 1 takes the lead by 7
    >>> f3 = f2(8, 12)
    >>> f4 = f3(8, 13)
    >>> f5 = f4(15, 13)
    Player 0 takes the lead by 2
    """
    def say(score0, score1):
        if score0 > score1:
            leader = 0
        elif score1 > score0:
            leader = 1
        else:
            leader = None
        if leader != None and leader != last_leader:
            print('Player', leader, 'takes the lead by', abs(score0 - score1))
        return announce_lead_changes(leader)
    return say

我了解 doctest 的工作原理,但是如何在 while 循環中實現它? 我嘗試了以下方法,但它繼續在整個循環中傳遞默認參數:

commentary = both(say_scores, announce_lead_changes())
while
    ...
    commentary(score0, score1)

更新 while 循環中每次迭代的commentary 嘗試:

commentary = both(say_scores, announce_lead_changes())
while
    ...
    commentary = commentary(score0, score1)

暫無
暫無

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

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