首页 > 解决方案 > Python在函数内部更改变量值时不保存变量值

问题描述

我在程序开始时保存了我的变量并允许函数访问它们我相信但是当它们运行时,当函数重复时不会保存值。

P1_score = 0
P2_score = 0
round_number = 0

def dice_rolling():
    # P1D1 means player ones dice one value and so on with P1D2
    import random
    # player ones turn
    print("player ones turn")
    P1D1 = random.randint(1, 6)
    print("your number is ", P1D1)
    P1D2 = random.randint(1, 6)
    print("your second number is", P1D2)
    # player twos turn
    print("player twos turn")
    P2D1 = random.randint(1, 6)
    print("your number is", P2D1)
    P2D2 = random.randint(1, 6)
    print("your second number is", P2D2)
    score_calculation(P1D1, P1D2, P2D1, P2D2,P1_score,P2_score,round_number)


def score_calculation(P1D1, P1D2, P2D1, P2D2,P1_score,P2_score,round_number):
    import random
    
    round_number = round_number + 1
    # player 1 score calculation
    total_P1 = P1D1 + P1D2
    P1_score = P1_score + total_P1
    if total_P1 % 2 == 0:
        P1_score = P1_score + 10
    else:
        P1_score = P1_score + 5
    if P1D1 == P1D2:
        P1D3 = random.randint(1, 6)
        P1_score = P1_score + P1D3

    # player 2 score calculation
    total_P2 = P2D1 + P2D2
    P2_score = P2_score + total_P2
    if total_P2 % 2 == 0:
        P2_score = P2_score + 10
    else:
        P2_score = P2_score + 5
    if P2D1 == P2D2:
        P2D3 = random.randint(1, 6)
        P2_score = P2_score + P2D3
    print("player ones score at the end of round", round_number, "is", P1_score)
    print("player twos score at the end of round",round_number,"is",P2_score)

    
for x in range(0,5):
    dice_rolling() 

任何帮助将不胜感激,如果有人可以简单地解释我做错了什么以及要解决什么问题,那就太好了。

标签: pythonpython-3.xpython-3.6

解决方案


Python 可以从函数内部的全局变量中读取,但如果没有一些额外的工作就无法分配它们。global通常,当您想使用全局变量时,最好通过在函数中使用关键字来使其显式化:

my_global_var = 0

def some_function():
    global my_gobal_var
    
    my_global_var = 10

print(my_global_var) # it prints 10

somefunction() # modifies the global var

print(my_global_var) # now it prints 10

推荐阅读