Search code examples
pythonfunctionlogic-error

Function is returning a different value each time it is called. How do I make it only change each time it while loop loops?


I am essentially making a text game of rock paper scissors vs the computer (random generated number) that stops when each player reaches 10 points for my class. I believe every time I call the compPick() function that it changes. This is problematic as the game is no longer works as intended.

#Rock, Paper, Scissors created by Manpreet Singh
from random import randint

userScore = 0
compScore = 0 

def compPick(): #generates a rand num 1-3 then returns that as the corresponding option
    guess = randint(1,3)
    if guess == 1:
        guess = 'Rock'
    elif guess == 2:
        guess = 'Paper'
    else:
        guess = 'Scissors'
        
    return guess


while userScore != 10 or compScore != 10:
    userPick = input("Rock, Paper or Scissors: ")
    print(compPick()) #print for debug
    userPick = userPick.title()
    
    if userPick == compPick():#Both pick the same
        print("Draw! No points.")
    elif userPick == 'Rock' and compPick()== 'Paper':
        print(compPick()) #print for debug
        compScore += 1
        print(f"+1 point for computer! \nC:{compScore} U:{userScore}")
    elif userPick == 'Paper' and compPick()== 'Rock':
        userScore += 1
        print(f"+1 point for computer! \nC:{compScore} U:{userScore}")
    elif userPick == 'Rock' and compPick()== 'Scissors':
        userScore += 1
        print(f"+1 point for computer! \nC:{compScore} U:{userScore}")
    elif userPick == 'Scissors' and compPick()== 'Rock':
        print(compPick()) #print for debug
        compScore += 1
        print(f"+1 point for computer! \nC:{compScore} U:{userScore}")
    elif userPick == 'Paper' and compPick()== 'Scissors':
        print(compPick()) #print for debug
        compScore += 1
        print(f"+1 point for computer! \nC:{compScore} U:{userScore}")
    elif userPick == 'Scissor' and compPick()== 'Paper':
        userScore += 1
        print(f"+1 point for computer! \nC:{compScore} U:{userScore}")
    else:
        print('error')

Solution

  • Create a variable that stores the compPick() result and use that to compare against the userPick. Otherwise you are correct, it will regenerate every time you call the compPick() function/method.