I made a Rock, Paper,Scissors game on Python. It is virtually finished, in fact you can alreay play the game with the current code. I am learning Python so I kept adding as more features as possible to practice. But I finally encountered something I could not work around. First, here is the code:
import random
player_Wins = 0
PC_Wins = 0
WinningConditions = {"paper":"rock","rock":"scissors","scissors":"paper"}
def PC():
PC_Selection = random.choice(list(WinningConditions))
print ("The PC chose " + PC_Selection + "!")
return PC_Selection
def Player():
playerSelection = input ("Let's play rock, paper, scissors! To choose your option, write rock, paper or scissors and press Enter: ")
if playerSelection.lower() in WinningConditions:
print ("\nYou chose" + " " + playerSelection + "!")
return playerSelection
else:
print ("\nInvalid option! You must choose rock, paper or scissors! Please try again!\n")
Player()
def ShowScore():
print ("Current score: \nYou have won " + str(player_Wins) + " times!\nThe PC has won " + str(PC_Wins) + " times! \n")
def QuitPlaying():
global player_Wins
global PC_Wins
Quit = input("Do you want to keep playing? \nPress 'Y' and then Enter to keep playing, Press 'N' and then Enter to quit playing.\n")
if Quit.lower() == "y":
return False
elif Quit.lower() =="n":
return True
else:
print ("\nInvalid option! Please enter 'Y' or 'N'!\n")
QuitPlaying()
def RockPaperScissors():
global player_Wins
global PC_Wins
while True:
player_option = Player()
PC_Option = PC()
if player_option == PC_Option:
print ("It's a tie!\n")
ShowScore()
if QuitPlaying():
break
elif WinningConditions[player_option] == PC_Option:
print ("You won!\n")
player_Wins += 1
ShowScore()
if QuitPlaying():
break
else:
print ("The PC wins!\n")
PC_Wins += 1
ShowScore()
if QuitPlaying():
break
print ("\nYou chose to quit playing.\nYou won" + " " + str(player_Wins) + " " + "times!\nThe PC won" + " " + str(PC_Wins) + " " + "times!")
if player_Wins > PC_Wins:
print ("You are the winner! Thanks for playing!")
elif PC_Wins > player_Wins:
print ("The PC is the winner! Thanks for playing!")
elif player_Wins == PC_Wins:
print ("Nobody won! It was a tie! Thanks for playing!")
RockPaperScissors()
The Error happens as follows: If I intentionally input an invalid option at first, when the Player must choose their option (for the sake of testing), and then after that I try to choose a valid option ("rock", "paper", or "scissors"), it gives me this error on Line 46:
elif WinningConditions[player_option] == PC_Option:
KeyError: None
Oddly, this only happens after entering correctly "rock", "paper" or "scissors" on a second try, after having entered an invalid option intentionally on the first try. If I write a correct option on the first try, the program runs completely smoothly. Any help with this Error would be greatly appreciated!