Recommand · November 24, 2021 0

Python – While loop rock paper scissor game

I have a simple rock paper game. I won’t it loop 5 times so I can have a best out of 5 games. Whenever I add a while loop it doesn’t work anymore. Can anyone help me with this? I tried adding count and win to the helper function but it couldn’t identify the variables. Could someone also explain why it wasn’t recognized in the helper function but in the "main" function it was?
enter image description here

When you return that puts an end to any loops that are happening inside of the function. To stop this from happening you would need to either print out when you win/lose/draw instead of returning the result, or move the while loop to happen outside of the play function.

I think you forgot to globalize your count and win variables. In addition your code seems to ask user input once and loop 5 times based on only one input. Here is some code that works.

import random

win = 0
count = 0

print("Welcome to Rock, Paper, Scissors. Best out of 5 wins!\n")

def play():
    global count
    global win
    while count < 5:
        count += 1
        print("Round",count)
        user = input("Rock, Paper, or Scissor? : \n").lower()
        computer = random.choice(["rock","paper","scissor"])
        print(f"Computer chose {computer}!")
        if user == computer:
            print("Draw!")
        else:
            if is_win(user,computer):
                print("You Win!")
                win += 1
            elif not is_win(user,computer):
                print("You lose")
        print("")
    print(f"You won {win} times!")
        
def is_win(player,opponent):
    if (player == "rock" and opponent == "scissor") or (player == "paper" and opponent == "rock") or (player == "scissor" and opponent == "paper"):
        return True
    else:
        return False

play()