npburns224 npburns224 - 1 year ago 93
Python Question

Function not updating global variable

I'm writing a program that simulates a game of Bunko for my compSci class, but I'm having issues getting the function

to modify the global variable
. The game pits a player against the computer, so I wanted to be able to use one function to determine the score and just pass an in argument to increment the correct score respectively. However, the function is not saving the value of
across multiple plays, resetting to 0 with each round. I'm new to functions, so I'm sure the issue is likely something trivial, but I appreciate any and all help!

dieList = []
sixCount = 0
playerScore = 0

def rollDice():
global sixCount
sixCount = 0

die1 = random.randint(1,6)
die2 = random.randint(1,6)
die3 = random.randint(1,6)



for x in dieList:
if x == 6:
sixCount += 1
print("sixCount:", sixCount)

def scoreCalc(x):
if sixCount == 1:
x += 1
elif sixCount == 2:
x += 5
elif sixCount == 3:
x += 21
return x

print("Player's turn!")
print('*' * 30)
input("Press ENTER to roll the dice")
print("Score:", scoreCalc(playerScore))

Answer Source

You clearly know how to modify a global variable, which you did for sixCount. You probably used to do that with playerScore, but changed it when trying to make the function useful for calculating anybody's score (stated goal in the OP).

In order to make the function work like a function, it needs to be ... a function. Meaning that it takes an input and gives an output, and nothing else matters. You then just need to use that output.

def scoreCalc(sixCount):
    x = 0
    if sixCount == 1:
        x += 1
    elif sixCount == 2:
        x += 5
    elif sixCount == 3:
        x += 21
    return x

# now use it
playerScore += scoreCalc(sixCount)

Notice how scoreCalc doesn't care about any global variables. It just gives the score for its input. You then apply that score where it belongs.

These functions might also be useful. It's better not to give them any global variables. Handle the results where they matter, and just let these functions do their job, and nothing else.

# return a list of d6 outputs
def rollDice(number_of_dice):
    return [random.randint(1,6) for _ in range(number_of_dice)]

# takes a list of d6 outputs and returns the count of sixes    
def countSixes(dieList):
    return sum([1 for x in dieList if x==6])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download