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):

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

in my com_move function, I don't see turn_score (which is outputting a random number through random module) adding it in comp_sc variable. when I run this function - comp_sc is always equal to turn_score - instead of adding up all the 5 turn_score in it.

Thank you

2 answers

  • answered 2021-09-11 18:02 Mureinik

    computer_score is a local variable inside the computer_move function. You are doing the correct thing by returning it, but then you just ignore this return value. Instead, you could assign it back to the computer_score variable in the calling function:

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

  • answered 2021-09-11 18:04 ph140

    It is because you write computerscore =+ turnscore which is setting computerscore to the positive value of turnscore, so they will always be the same.

    The right way would be to write computerscore += turnscore which will add the turnscore to the computerscore.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum