python - Redefining a variable inside a loop -
i having problem getting 'undefined' error in code or, variable being incorrectly redefined. trying redefine variable inside loop each time loop executed. problem either (when variable defined outside loop) 'variable undefined' error, or variable not change and/or reset 0 when loop reinitialized.
def game(): scoreplayer = 0 scoreai = 0 #if define here latter of 2 errors explained. number = random.randint(1, 6) print ("your score ", scoreplayer, ". opponent's score ", scoreai, ".") #this tells me referenced before defined if define outside loop. print (" ") print ("rolling...") print (" ") time.sleep(2) print ("you have rolled ", number, ".") print (" ") print ("player, hold (enter 'hold') or roll (enter 'roll')?") print (" ") decide = raw_input(" ") if decide == 'hold': print (" ") scoreplayer = tempscoreplayer + scoreplayer gameai() elif decide == 'roll': #changed elif print (" ") if number == 1: print ("you have rolled 1. not gain points turn.") print (" ") tempscoreplayer = 0 gameai() elif number >= 2: #changed elif print (" ") tempscoreplayer = number + tempscoreplayer game() if scoreplayer >= 100: winplayer()
i have tried defining variables everywhere else wouldn't interfere loop , still couldn't work.
any appreciated, thanks.
try one:
def game(): scoreplayer = 0 scoreai = 0 #if define here latter of 2 errors explained. number = random.randint(1, 6) print ("your score %d. opponent's score %d."%(scoreplayer, scoreai)) #this tells me referenced before defined if define outside loop. print (" ") print ("rolling...") print (" ") time.sleep(2) print ("you have rolled %d.", number) print (" ") print ("player, hold (enter 'hold') or roll (enter 'roll')?") print (" ") decide = raw_input(" ") if decide == 'hold': print (" ") scoreplayer += tempscoreplayer gameai() if decide == 'roll': tempscoreplayer = 0 print (" ") if number == 1: print ("you have rolled 1. not gain points turn.") print (" ") gameai() if number >= 2: print (" ") tempscoreplayer += number game() if scoreplayer >= 100: winplayer()
i changed tempscoreplayer variable, setting 0 @ default.
note: tempscoreplayer += number
it's equals tempscoreplayer = tempscoreplayer + number
Comments
Post a Comment