[Python] Problem when running Python rock, paper and scissors game code [closed]

Discussão em 'Python' iniciado por Stack, Maio 4, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to write a simple program that simulates a rock, paper, scissors game. When trying to run the code for the first time, the system returns an error:

    Traceback (most recent call last):
    File "C:/Users/RRM/Documents/Python/rockpaperScissors.py", line 40, in <module>
    computerMove == 's'
    NameError: name 'computerMove' is not defined


    What's funny is, it only happens when I run the codes from the code editor (IDLE) for the first time. If I ignore this error and re-run the codes again, the problem is gone and the game works as intended.

    Below are my codes:

    import random, sys

    print('ROCK, PAPER, SCISSORS')

    #these variables keep track of the number of wins, losses, and ties

    wins = 0
    losses = 0
    ties = 0

    while True: #the main game loop
    print('%s Wins, %s Losses, %s Ties' % (wins, losses, ties)) #assign the symbol '%' to wins, losses and ties
    while True: #the player input loop (to make the player type either 'r','p','s' or 'q')
    print('Enter your move: (r)ock (p)aper (s)cissors or (q)uit')
    playerMove = input()
    if playerMove == 'q':
    sys.exit() #quit the program
    elif playerMove == 'r' or playerMove == 'p' or playerMove == 's':
    break #break out of the loop of telling the player to type either 'r','p','s' or 'q'
    else:
    print('Please choose between r, p, and s.')

    #display what the player chooses
    if playerMove == 'r':
    print('ROCK versus ...')
    elif playerMove == 'p':
    print('PAPER versus ...')
    elif playerMove == 's':
    print('SCISSORS versus ...')

    #display what the computer choose
    randomNumber = random.randint(1,3)
    if randomNumber == 1:
    computerMove = 'r'
    print('ROCK')
    elif randomNumber == 2:
    computerMove = 'p'
    print ('PAPER')
    elif randomNumber == 3:
    computerMove == 's'
    print ('SCISSORS')

    #Result of the round
    if playerMove == computerMove:
    print('TIE')
    ties = ties + 1
    elif playerMove == 'r' and computerMove == 's':
    print('WIN')
    wins = wins + 1
    elif playerMove == 'r' and computerMove == 'p':
    print('LOSE')
    losses = losses + 1
    elif playerMove == 'p' and computerMove == 'r':
    print('WIN')
    wins = wins + 1
    elif playerMove == 'p' and computerMove == 's':
    print('LOSE')
    losses = losses + 1
    elif playerMove == 's' and computerMove == 'p':
    print('WIN')
    wins = wins + 1
    elif playerMove == 's' and computerMove == 'r':
    print('LOSE')
    losses = losses + 1


    I don't understand why the system told me that the name computerMove in computerMove == 's' is not defined. It is clearly defined as 's' or scissors when the program picks the number 2.

    Continue reading...

Compartilhe esta Página