I’m writing a program in which the user plays a number guessing game with the computer. The computer chooses it’s number using random. I seem to be running into this error after the user inputs their number. Any idea why? The variable seems to be fine above in the if statement.
import random
player_score = 0
computer_score = 0
restart = 'Y'
stop = 'N'
print("Can you test your luck against the computer?n Guess the number the computer is
thinking, and you win!")
print("---------------------------------------------------------------------------------------------------------------------------------------")
def game():
player_choice = int(input("Please chose a number: "))
computer_choice = random.randint(0, 5)
if player_choice == computer_choice:
player_score += 1
print("You win!nComputer Score: ",computer_score," Player Score: ",player_score)
elif player_choice != computer_choice:
computer_choice += 1
print("Computer wins...nComputer Score: ",computer_score," Player Score: ",player_score)
2
Answers
as commented by @johnrsharper you need to define global to access variable from inside function:
You need to make
player_score
global.Helpful link