多次调用函数;如何添加返回值;蟒蛇

时间:2017-08-22 20:24:40

标签: python python-3.x function sum

我正在使用Python 3.5创建一个游戏。

我有一个返回分数的函数,我想在每次调用函数时对分数求和,以获得最终分数。

简化代码如下:

letter = 'b'

def func(letter):

    score = 0
    word='bye'

    for i in word:
        if letter == i:

            new_word = REMOVE THIS LETTER FROM WORD

            score += 1
            return(new_word, score)
        else:
            return('TRY AGAIN')

现在假设在另一个函数中多次调用此函数,如何将这些分数一起添加以产生最终分数?

如果我的简化代码看起来有点错误,我主要担心的是如何将函数的数值回归相加。

由于

1 个答案:

答案 0 :(得分:1)

创建一个在函数外部初始化的新变量totalScore,并在每次调用函数时更新它。

letter = 'b'
totalScore = 0

def func(letter):

    score = 0
    word='bye'

    for i in word:
        if letter == i:

            new_word = REMOVE THIS LETTER FROM WORD

            score += 1
            totalScore += score
            return(new_word, score)
        else:
            return('TRY AGAIN')

然后,只要其他功能需要,您就可以访问totalScore