Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Declaring a variable in a function but making value change accordingly

Here is my full code:

import random

def play():
  userScore = 0
  computerScore = 0

  userChoice = input("Choose r for rock, p for paper and s for \
scissor ")                 
  computerChoice = random.choice(["r", "p", "s"])
  print(computerChoice)
  
  if userChoice == computerChoice:
    print("Tie")
    print ("User:" + str(userScore) + " computer:" + str(computerScore))

  elif (userChoice == "r" and computerChoice == "s") or (userChoice == "p" and computerChoice == "r") or (userChoice  == "s" and computerChoice == "p"):
    print("You won!")
    userScore = userScore + 1
    print ("User:" + str(userScore) + " computer:" + str(computerScore))

  else:
    print("You lost :(")
    computerScore = computerScore + 1
    print ("User:" + str(userScore) + " computer:" + str(computerScore))
    

  play()

play()

My problem is that the 2 variables for score, userScore and computerScore gets declared in the function again with the value 0. My goal is to have them increase whenever the user loses or wins, so that’s not optimal. When I try to declare them outside of the function, I get an error where it says that they are referenced before initialized. It makes sense, but I don’t know what to do. Is there a way to declare them within the function but with different value according to how many times the user or the computer has won, or just in general other ways to approach this problem?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One way to approach this that doesn’t involve global or object state would be to take the current scores as arguments:

def play(userScore=0, computerScore=0):

    # ... rest of function

    play(userScore, computerScore)  # recurse with updated scores

play()  # starting score is 0, 0

Since you want play() to repeat in an infinite loop, though, it would be simpler to keep these variables local and just use a while loop inside the function:

import random

def play():
    user_score = 0
    cpu_score = 0
    winning_pairs = ("rs", "pr", "sp")  # 'r' beats 's', etc
    while True:
        user_choice = input("Choose r for rock, p for paper and s for scissor ")
        cpu_choice = random.choice(["r", "p", "s"])
        print(cpu_choice)
        if user_choice == cpu_choice:
            print("Tie")
        elif user_choice + cpu_choice in winning_pairs:
            print("You won!")
            user_score += 1
        elif cpu_choice + user_choice in winning_pairs:
            print("You lost :(")
            cpu_score += 1
        else:
            print(f"What's a '{user_choice}?")
            user_score -= 1

        print (f"User: {user_score} computer: {cpu_score}")

play()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading