Click here to Skip to main content
15,888,984 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I made a number guessing with a loop that restarts. But when the loop restarts the score system gets reset to 0 as I have set a variable to track score and on loop it is first set to 0 then using `score=score+1` I can track score but when it loops it just becomes 0 then gets set to 1?



I've tried taking the score out of the loop but it comes back with a `local variable 'score' referenced before assignment`.


Python
<pre>
from random import *                                                

                                                                    
yesList = ("yes", "yeah", "sure", "definitely", "y", "ye", "yeah")  
                                                                   

def win():                                             
        print("Correct")                                            
        print("You have won", Pname + "!")                         
        print("I've added 1 point to your score!") 
        score = int("0")
        score= score+1                                                
        print("You've scored", score, "points!")
        restart()                                                   




Pname = input("What is your name? ")                                
print("Hello", Pname, "let's play a game.")                       


def restart():                                                     
  restart=input("Do you want to play again? ").lower()             
  if restart in yesList:                                            
    main()                                                         
  else:
    print("Game Over")
    print("You scored", score, "points!")
    exit()
    
def main():                                                       
  
  rnum = randint(1, 100)                                            
  
  num1 = int(input("Guess a number between 1 and 100: "))        
  if num1 == rnum:
        win()
      
  elif num1>rnum: 
        print("Too High")

  else: 
        print("Too Low")

      
      
  num2 = int(input("Guess again: "))
  if  num2==rnum:
          win()
      
  elif num2>rnum: 
        print("Too High")
      
  else: 
        print("Too Low")

  num3 = int(input("Guess again: "))
  if  num3==rnum:
        win()

  elif num3>rnum: 
        print("Too High")
      
  else: print("Too Low")

  num4 = int(input("Guess again: "))
  if  num4==rnum:
          win()
      
  elif num4>rnum: 
        print("Too High")
      
  else: 
        print("Too Low")
      
  num5 = int(input("Guess again: "))
  if  num5==rnum:
          win()
      
  elif num5>rnum: 
        print("Too High")
      
  else: 
        print("Too Low")
  
  
  num6 = int(input("Guess again: "))
  if  num6==rnum:
          win()
      
  elif num6>rnum: 
        print("Too High")
      
  else: 
        print("Too Low")
  
  
  num7 = int(input("Guess again: "))
  if  num7==rnum:
          win()
      
  elif num7>rnum: 
        print("Too High")
      
  else: 
        print("Too Low")
  str(print("The answer is", rnum))
  
  restart()
  
score=0
main()


What I have tried:

Traceback (most recent call last):
  File "program.py", line 115, in <module>
    main()
  File "program.py", line 40, in main
    win()
  File "program.py", line 14, in win
    score= score+1                                             
UnboundLocalError: local variable 'score' referenced before assignment

This is the error message that comes when you take the score out of the loop.
Posted
Updated 7-Jun-19 10:45am

In addition to Richard's solution:

This happens because Python thinks score is a local variable, but it isn't. To make your current code work, you need to tell Python that score is a global variable. Add this line as the first line of your win function:
Python
global score

And then you can take the score = int("0") out of your win method.
 
Share this answer
 
You should create a class so the score variable is available to all its methods. Alternatively you can pass the score variable as a parameter to each of the existing methods. See 4. More Control Flow Tools : defining-functions[^].
 
Share this answer
 
Quote:
How do you add a point system within a loop that continues tracking points when the loop has restarted?

As spotted in previous solutions:
Python
score = int("0") # this is enough to prevent the score from working
score= score+1

But, you have another problem:
You are looping without using any loop statement, this means that you are looping by infinitely calling sub routines, and this is a bad programming style.
Ok, it works on this toy program, but it must be avoided at all cost in any serious program.
You need to learn what are loops and how to use them.
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training | Edureka - YouTube[^]
Python 3 Programming Tutorial - For loop - YouTube[^]
 
Share this answer
 
Here is a code you can use instead:

#Random number and date/time is imported
import random
from datetime import datetime

currenttime = str(datetime.now())
currenttime = (
currenttime[0:19]) #Ensures that only the first 19 digits of the date and time is displayed
YES_LIST =("yes", "sure", "yeah", "ye", "yea", "y", "fine", "okay", "ok", "yep")
score = 0 #To add a point system score must equal to 0 at the start of the game
GuessesTaken2 = 0 #GuessesTaken2 calculates the total guesses out of all the games played by player so this information can be exported into the text file 

Name = input("What is your name? ") #game asks for player's name
print("Hello {}, Let's play a number guessing game. I am thinking of a number between 1 and 100.".format(Name))

#game begins
def main(): 
    
    hidden = random.randint(1,100) #random number between 1 and 100 is generated
    GuessesTaken = 0 # used to calcualte the guesses taken each game
    while GuessesTaken < 6: #loop that automatically breaks after 6 guesses

        guess = int(input("Guess which number I am thinking of: "))
        GuessesTaken = GuessesTaken + 1;
        global GuessesTaken2 #assigning GuessesTaken2 as a global function will allow the game to use it outside the loop
        GuessesTaken2 = GuessesTaken2 + 1;
        GuessesLeft = 6 - GuessesTaken; #algorithm to figure out how many guesses are left
    
        if guess > hidden and GuessesLeft==0: #when there are no guesses left and the guessed number is higher than the actual number, the loop is automatically broken
            print("Your guess is too high, you are unfortunately out of guesses!")
            print("The number I was thinking of was actually {}".format(hidden))
            restart()
        
        if guess > hidden and GuessesLeft > 0: #If the guess is too high but there are still guesses left, the game allows you to guess again
            print("Your guess is too high, you have {} guess/es left".format(GuessesLeft))
        
        if guess < hidden and GuessesLeft==0: #when there are no guesses left and the guessed number is lower than the actual number, the loop is automatically broken
            print("Your guess is too low and you are unfortunately out of guesses!")
            print("The number I was thinking of was actually {}".format(hidden))
            restart()
        
        if guess < hidden and GuessesLeft > 0: #If the guess is too low but there are still guesses left, the game allows you to guess again
            print("Your guess is too low, you have {} guess/es left".format(GuessesLeft))
        
        if guess==hidden: #When the number is guessed correctly, the player gains points
            global score #assigining score as a global function will allow the game to use it outside the loop
            score = score + 5 #score increases by  5 each time you guess the number correctly
            print("Hit!")
            print("Congratulations {} !".format(Name))
            print("It took you {} guesses to correctly guess the number correctly.".format(GuessesTaken))
            print("Your points go up by 5! You are currently on {} points.".format(score))
            restart()

def restart(): #allows the player to play again if he/she wishes
    restart=input("Would you like to play again?").lower()
    if restart in YES_LIST: # only occurs if the player's response is with the YES_LIST that was made earlier
        main() #the game restarts
    else: #
        if score==0:
            print("GAME OVER!", "Horrific, You didn't even manage to get a point.") 
        elif score>1:
            print("GAME OVER!", "Good Job, You've managed to get {} points".format(score))
      
    text_file = open(Name + " game details.txt", "w") #opens up a text file with all the game details if the player does not choose to playa again
    text_file.write("Player Name: {} \nTime and date: {} \nNumber of Guesses: {} (altogether out of all the games you played) \nScore: {}".format(Name, str(currenttime), str(GuessesTaken2), str(score)))
    text_file.close()
    exit() #exits the game if player does not choose to play again

main() #allows the game to run 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900