在 python 中的函数中操作变量

manipulate variables in a function in python

comp_sc = 0
game_start = False

def main():
    turn_start = input('Are you Ready to play? ').lower()
    if turn_start == 'n':
        game_start = False
        print('No one is willing to play!!!')
    if turn_start == 'y':
        game_start = True

    #while game_start == True:
    for x in range(1, 5):
        com_move(comp_sc)

def roll():
    ***


def com_move(comp_sc):
    turn_score = int(roll())
    if turn_score < 6:
        comp_sc =+ turn_score
        print(comp_sc, 'comp_sc')
    elif turn_score == 6:
        comp_sc =+ 0
        game_start = False
    return comp_sc

在我的 com_move 函数中,我没有看到 turn_score(通过随机模块输出随机数)将其添加到 comp_sc 变量中。当我 运行 这个函数时 - comp_sc 总是等于 turn_score - 而不是将其中的所有 5 turn_score 相加。

谢谢

computer_scorecomputer_move 函数内的 local 变量。您通过 returning 来做正确的事情,但是您只是忽略了这个 return 值。相反,您可以将其分配回调用函数中的 computer_score 变量:

for x in range(1, 5):
    computer_score = computer_move(computer_score, human_score)

因为你写的computerscore =+ turnscore是把computerscore设置为turnscore的正值,所以他们永远是一样的。

正确的方法是编写 computerscore += turnscore,这会将 turnscore 添加到 computerscore。