I changed a bit!


#1


I saw other's Topic and changed a bit and wrote this in my way..
but it doesnt work with this Error.

Traceback (most recent call last):
File "python", line 39, in
File "python", line 26, in game
File "python", line 32, in decide_winner
UnboundLocalError: local variable 'rounds' referenced before assignment

In this way, I didnt consider anything except winning like draw.
and I'd like to run this until 3 times.
Can anyone explain where is wrong ?? :sweat:


Replace this line with your code. 
from random import randint
rounds = 1

rules = {
    1: 'rock',
    2: 'paper',
    3: 'scissors'
}
    
rules2 = {
    1: 'scissors',
    2: 'rock',
    3: 'paper'
}

def game():
    print "rounds", rounds
    player = int(raw_input(
'Enter a number:\nRock: 1\nPaper: 2\nScissors: 3'))
    cpu = randint(1,3)
    print player
    print cpu
    print
    print
    print "You picked %s and Computer picked %s" %(rules[player], rules2[cpu])
    decide_winner(player, cpu)
    
def decide_winner(player, cpu):
    if player == cpu:
        print "YOu Win!"
    while player != cpu:
        rounds +=1
        game()
        if rounds >3:
            break
        else:
            print "Try agian"
        
game()


#2

Do this instead:

for _ in range(3):
    game()

(nothing special about underscore, just a name convention for "not going to use this")

MUCH more clear what's going on.

Problem is you were reading a local variable before giving it a value, just like Python was saying. You can work around that by saying that you want to use the global variable instead, but there's no point when the above is just.. better


#3

Oh.. You weren't repeating the game. Well. Use a local variable then, no need to store that globally, that's kind of like storing food outside your apartment in the stairwell, just doesn't belong there.


#4

from random import randint

rules = {
1: 'rock',
2: 'paper',
3: 'scissors'
}

rules2 = {
1: 'scissors',
2: 'rock',
3: 'paper'
}
for rounds in range(2):
print "round", rounds +1
player = int(raw_input(
'Enter a number:\nRock: 1\nPaper: 2\nScissors: 3'))
cpu = randint(1,3)
print player
print cpu
print "You picked %s and Computer picked %s" %(rules[player], rules2[cpu])
start=True
while start:
if player == cpu:
print "YOu Win!"
break
else:
print "Try Agian"
if rounds>3:
break

I tried like this but I can't stop "Try Again"s.............
even I wrote break!
Can you tell me what is problem??


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.