Rock Paper Scissors Game. Trouble with defining terms - python

This is the largest program I've made so far my problem is that my program won't run because the variable cpu isn't defined. I've tried different approaches but still nothing. Here is my code, also is there anyway to shorten my code? I felt I made alot of repetitive lines. I suspect that my problem is in the def cpu_choice(). Also this program dosent seem to give any output after its done.
#This program will execute a Rock,Paper,Scissors Game.
import random
get = int(input('Enter a number 1 to 3 as your choice.\n'))
def cpu_choice():#This function is for the computer to get a option.
list_option = [1 , 2, 3]
cpu = random.choice(list_option)
return(random.choice(list_option))
if cpu == 1:
cpu = "Rock"
if cpu == 2:
cpu = 'Paper'
if cpu == 3:
cpu = 'Scissor'
def compare(cpu,get):
again = 'y'
while again == 'y' or again == 'Y':
if get == cpu:
print('Its a tie!')
again = input('Enter Y or y to play again. Enter N or n to quit.')
if again == 'y' or again == 'Y':
main(cpu)
if again == 'n' or 'N':
again = False
#Checks to see if it is a tie
elif cpu == 'Rock' and get == 'Scissor':
print('You win!')
again = input('Enter Y or y to play again. Enter N or n to quit.')
if again == 'y' or again == 'Y':
main(cpu)
if again == 'n' or 'N':
again = False
#Compares when CPU picks Rock.
elif cpu == 'Rock' and get == 'Paper':
print('You lose.')
again = input('Enter Y or y to play again. Enter N or n to quit.')
if again == 'y' or again == 'Y':
main(cpu)
if again == 'n' or 'N':
again = False
elif cpu == 'Paper' and get == 'Rock':
print('You win!')
again = input('Enter Y or y to play again. Enter N or n to quit.')
if again == 'y' or again == 'Y':
main(cpu)
if again == 'n' or 'N':
again = False
elif cpu == 'Paper' and get == 'Scissor':
print('You lose.')
again = input('Enter Y or y to play again. Enter N or n to quit.')
if again == 'y' or again == 'Y':
main(cpu)
if again == 'n' or 'N':
again = False
elif cpu == 'Scissor' and get == 'Paper':
print('You win!')
#This will decide the outcome when the computer picks paper.
again = input('Enter Y or y to play again. Enter N or n to quit.')
if again == 'y' or again == 'Y':
main(cpu)
if again == 'n' or 'N':
again = False
elif cpu == 'Scissor' and get == 'Rock':
print('You lose.')
again = input('Enter Y or y to play again. Enter N or n to quit.')
if again == 'y' or again == 'Y':
main(cpu)
if again == 'n' or 'N':
again = False
#This decides the outcome if the computer picks scissors.
def main(cpu,get):# Executes the programs and checks to see if the input is valid.
print('Rock = 1')
print('Paper = 2')
print('Scissor = 3')
again = 'y'
while get < 1:
get = int(input('Enter a valid number.'))
while get > 3:
get= int(input('Enter a valid number.'))
if get == 1:
get = "Rock"
if get == 2:
get = 'Paper'
if get == 3:
get = 'Scissor'
cpu_choice()
compare(cpu,get)
main(cpu,get)

Your cpu_choice should look like this:
def cpu_choice():#This function is for the computer to get a option.
list_option = [1 , 2, 3]
cpu = random.choice(list_option)
if cpu == 1:
cpu = "Rock"
if cpu == 2:
cpu = 'Paper'
if cpu == 3:
cpu = 'Scissor'
return cpu
This is because a return will exit the function so any code behind a return statement in a function will never be executed.
Your main function should look like this:
def main(cpu,get):# Executes the programs and checks to see if the input is valid.
print('Rock = 1')
print('Paper = 2')
print('Scissor = 3')
again = 'y'
while get < 1:
get = int(input('Enter a valid number.'))
while get > 3:
get= int(input('Enter a valid number.'))
if get == 1:
get = "Rock"
if get == 2:
get = 'Paper'
if get == 3:
get = 'Scissor'
compare(cpu,get)
You don't need to declare a cpu in your main function as you already pass a cpu to your main function.
Outside of your functions you will need this:
get = int(input('Enter a number 1 to 3 as your choice.\n'))
cpu = cpu_choice()
main(cpu,get)
Now your main function has all the parameters it needs. Note I placed get = int(input('Enter a number 1 to 3 as your choice.\n')) after the declaration of your functions. This is a common practice making understanding your code much easier.
Qua Optimisation
Pythons random can choose a random element from a list:
Or's can be used to make one elif for if you win and 1 for if you lose.
Considering that you call main() from within compare() it is best for main() to have no parameters but rather get get and cpu in the main function
A while statement can have multiple comparisons.
An optimised code would look like this:
import random
def cpu_choice():
list_option = ["Rock" , "Paper", "Scissor"]
cpu = random.choice(list_option)
return cpu
def compare(cpu,get):
if get == cpu:
print('Its a tie!')
again = input('Enter Y or y to play again. Enter N or n to quit.')
if again == 'y' or again == 'Y':
main()
elif cpu == 'Rock' and get == 'Scissor' or cpu == 'Paper' and get == 'Rock' or cpu == 'Scissor' and get == 'Paper':
print('You lose.')
again = input('Enter Y or y to play again. Enter N or n to quit.')
if again == 'y' or again == 'Y':
main()
elif cpu == 'Rock' and get == 'Paper' or cpu == 'Paper' and get == 'Scissor' or cpu == 'Scissor' and get == 'Rock':
print('You win!')
again = input('Enter Y or y to play again. Enter N or n to quit.')
if again == 'y' or again == 'Y':
main()
def main():
print('Rock = 1')
print('Paper = 2')
print('Scissor = 3')
get = int(input('Enter a number 1 to 3 as your choice.\n'))
cpu = cpu_choice()
while not 4 > get > 0:
get = int(input('Enter a valid number.'))
if get == 1:
get = "Rock"
if get == 2:
get = 'Paper'
if get == 3:
get = 'Scissor'
compare(cpu,get)
main()

At the bottom, you are calling main with the parameters 'cpu', which is undefined, and 'get', which is defined by user input at the top. This program takes 1 input and prints an output - you don't need to feed the cpu parameter to main since it is generated from what the cpu_choice function returns. Just get rid of that as a parameter and write cpu = cpu_choice() before you call compare, and have cpu_choice() return the cpu value.

you should modify your cpu_choice function to return a value. In addition, your return statement should also be removed, as explained in the comment next to it:
def cpu_choice(): #This function is for the computer to get a option.
list_option = [1 , 2, 3]
cpu = random.choice(list_option)
#return(random.choice(list_option)) #This returns a number, but in your compare code you are comparing strings, so take this line out
if cpu == 1:
cpu = "Rock"
if cpu == 2:
cpu = 'Paper'
if cpu == 3:
cpu = 'Scissor'
return cpu
in your main function, you can set another variable called cpu to the return value of your function called cpu_choice
def main(cpu,get): #Executes the programs and checks to see if the input is valid.
print('Rock = 1')
print('Paper = 2')
print('Scissor = 3')
again = 'y'
while get < 1:
get = int(input('Enter a valid number.'))
while get > 3:
get= int(input('Enter a valid number.'))
if get == 1:
get = "Rock"
if get == 2:
get = 'Paper'
if get == 3:
get = 'Scissor'
cpu = cpu_choice()
compare(cpu,get)

With a few corrections it's working: (read the comments)
import random
def cpu_choice():
list_option = [1 , 2, 3]
cpu = random.choice(list_option)
if cpu == 1:
cpu = "Rock"
if cpu == 2:
cpu = 'Paper'
if cpu == 3:
cpu = 'Scissor'
return cpu # the return goes here
def compare(cpu,get):
# you are using too many checks for again
# I'm moving the again checks out of here
# Moreover, all the results (win, lose) where wrong if you are 'get'
print("You -> " + get + " - " + cpu + " <- CPU")
if get == cpu:
print('Its a tie!')
elif cpu == 'Rock' and get == 'Scissor':
print('You lose!')
elif cpu == 'Rock' and get == 'Paper':
print('You win.')
elif cpu == 'Paper' and get == 'Rock':
print('You lose!')
elif cpu == 'Paper' and get == 'Scissor':
print('You win.')
elif cpu == 'Scissor' and get == 'Paper':
print('You lose!')
elif cpu == 'Scissor' and get == 'Rock':
print('You win.')
def game(): # Don't call it main please, and no need for the arguments
print('Rock = 1')
print('Paper = 2')
print('Scissor = 3')
get = int(input('Enter a number 1 to 3 as your choice.\n'))
while (get < 1) or (get > 3): # No need for two while loops
get = int(input('Enter a valid number.'))
if get == 1:
get = "Rock"
if get == 2:
get = 'Paper'
if get == 3:
get = 'Scissor'
# Or you can use this
# symbols = ["Rock","Paper","Scissor"]
# get = symbols[get-1] # it's better if you don't call both variables 'get'
cpu = cpu_choice() # you need to assign a value to cpu here
compare(cpu,get)
# I put the again code here
again = input('Enter Y or y to play again. Enter N or n to quit.')
if again in ['y','Y']:
game()
else:
print("Bye!")
if __name__ == "__main__": # This is the main
game()

Related

If statement only showing else portion

I'm writing code for a rock, paper, scissors game but the if statement in the function identify_winner is not running. The only thing that prints out is the else statement and it prints out for all outcomes, not just when it's a tie. I'm pretty sure it has something to do with the variables but I don't know what it is.
import random
ROCK = 1
PAPER = 2
SCISSORS = 3
def main():
user_choose(None)
comp_choose(None)
identify_winner()
def user_choose(weapon):
weapon = int(input('Choose Your Weapon' + '\n (Rock = 1, Paper = 2' +\
' Scissors = 3): '))
if weapon == 1:
print('You have chosen Rock')
elif weapon == 2:
print('You have chosen Paper')
elif weapon == 3:
print('You have chosen Scissors')
def comp_choose(choice):
if random.randint(1,3) == 1:
choice = 'Rock'
elif random.randint(1,3) == 2:
choice = 'Paper'
else:
choice = 'Scissors'
print('Your enemy has chosen',choice)
def identify_winner():
user = 0
comp = 0
while user == comp:
user_choose(user)
comp_choose(comp)
if (user == 1 and comp == 3) or (user ==2 and comp == 1) or (user == 3 and comp
== 2):
print('Congratulations! You have defeated the foe!')
elif (comp ==1 and user == 3) or (comp == 2 and user == 1) or (comp == 3 and
user == 2):
print('Alas, you have been defeated! Better luck next time!')
else:
print('Oh no, a tie! choose again!')
main()
First and foremost it is not a good practice to call main function directly as it was a script. If you plan to create not script program you should scope main function inside.
if __name__ == "__main__":
main()
Secondly, you don't need to call user_choose and comp_choose inside identify winner, you can just return those values in your main program and give them as arguments to your identify winner function. Also you should not generate two times a random number in your comp_choose() because in the second elif you could generate the previous number so comp choice most likely be Scissors. I give you one possible solution to your problem:
import random
ROCK = 1
PAPER = 2
SCISSORS = 3
def main():
identify_winner(user_choose(), comp_choose())
def user_choose():
weapon = int(input('Choose Your Weapon' + '\n (Rock = 1, Paper = 2' +\
' Scissors = 3): '))
if weapon == 1:
print('You have chosen Rock')
elif weapon == 2:
print('You have chosen Paper')
elif weapon == 3:
print('You have chosen Scissors')
return weapon
def comp_choose():
comp_weapon = random.randint(1,3)
if comp_weapon == 1:
choice = 'Rock'
elif comp_weapon == 2:
choice = 'Paper'
else:
choice = 'Scissors'
print('Your enemy has chosen',choice)
return comp_weapon
def identify_winner(user, comp):
if (user == 1 and comp == 3) or (user ==2 and comp == 1) or (user == 3 and comp
== 2):
print('Congratulations! You have defeated the foe!')
elif (comp ==1 and user == 3) or (comp == 2 and user == 1) or (comp == 3 and
user == 2):
print('Alas, you have been defeated! Better luck next time!')
else:
print('Oh no, a tie! choose again!')
if __name__ == "__main__":
main()
I made some little changes in your code. Commented the parts for explanation:
import random
# you never use those, so they are not needed here:
# ROCK = 1
# PAPER = 2
# SCISSORS = 3
def user_choose(): # no input argument needed since you define weapon in the next line anyway
weapon = int(input('Choose Your Weapon' + '\n (Rock = 1, Paper = 2' +\
' Scissors = 3): '))
# this part is asking for a number as long as user don't choose a valid number between 1 and 3.
# You could do even more here, check for number or letter, check if number is 0 or negative
while weapon>3:
weapon = int(input('No valid number. Please choose again: ' + '\n (Rock = 1, Paper = 2' +\
' Scissors = 3): '))
if weapon == 1:
print('You have chosen Rock')
elif weapon == 2:
print('You have chosen Paper')
elif weapon == 3:
print('You have chosen Scissors')
return weapon # you need to return the variable weapon, otherwise it is only in the local scope and your main function doesn't have access to it
def comp_choose(): # same as in the other function, no input argument needed
choice = random.randint(1,3) # in your code random.randint(1,3) executes twice and can have two different results. You want it once and then check on it
if choice == 1:
chose = 'Rock' # in the main() func you compare the numbers, but in your code user has numbers between 1 and 3 and comp has values with rock, paper, scissors.
elif choice == 2:
chose = 'Paper'
else:
choice = 3
chose = 'Scissors'
print('Your enemy has chosen',chose)
return choice # same as in the other function with 'weapon'
def main(): # identy_winner() isn't needed. two functions for user and comp with the main to select winner is enough
run = True
while run: # doing it like this you can make the user choose if he wants to continue or not (later at the 'continue_playing' part)
user = user_choose() # get access to the return value of the function
comp = comp_choose() # get access to the return value of the function
if (user == 1 and comp == 3) or (user ==2 and comp == 1) or (user == 3 and comp
== 2):
print('Congratulations! You have defeated the foe!')
elif (comp ==1 and user == 3) or (comp == 2 and user == 1) or (comp == 3 and
user == 2):
print('Alas, you have been defeated! Better luck next time!')
else:
print('Oh no, a tie! choose again!')
continue_playing = input('You want to play again? [y/n]: ')
if continue_playing == 'n':
run = False
main()
The code will crash if the user chooses a letter instead of numbers, and working poorly if he chooses numbers 0 or less. You may want to check for that.... I leave that up to you.

scissors paper stone game without the use of list in python

im new to this python program and was tasked to generate a game or scissors paper stone game in python without the use of a list. i have the function here as:
def getRandomShape():
Shape = random.randint(1, 3)
if Shape == 1:
print('Scissors'.upper())
elif Shape == 2:
print('Stone'.upper())
else:
print('Paper'.upper())
getRandomShape()
but whenever i call for the function, it says its not defined.
the error occurse at the possibleHands section where im unable to call for the function but able to at the bottom for the checkForWinner function call
here's the full program.
import random
print('welcome to scissors paper stone')
cpuScore = 0
playerScore = 0
tieScore = 0
possibleHands = getRandomShape(computerHand)
def getRandomShape(computerHand):
Shape = random.randint(1, 3)
if Shape == 1:
print('Scissors'.upper())
elif Shape == 2:
print('Stone'.upper())
else:
print('Paper'.upper())
def checkForWinner(playerHand, computerHand):
if(playerHand == 'Stone' and computerHand == 'Paper'):
print('you lost')
return 'cpu'
elif(playerHand == 'Stone' and computerHand == 'Scissors'):
print('you won')
return 'player'
elif(playerHand == 'Scissors' and computerHand == 'Paper'):
print('you won')
return 'player'
elif(playerHand == 'Scissors' and computerHand == 'Stone'):
print('you lost')
return 'cpu'
elif(playerHand == 'Paper' and computerHand == 'Scissors'):
print('you lost')
return 'cpu'
elif(playerHand == 'Paper' and computerHand == 'Stone'):
print('you won')
return 'player'
else:
print('its a tie. play again')
return 'tie'
while(playerScore != 3 and cpuScore != 3):
name = input('Please enter your name: ')
while True:
playerHand = (input('Round 1: '+str(name)+ ', please choose a shape:'))
if(playerHand == 'Scissors' or playerHand == 'Paper' or playerHand == 'Stone'):
break
else:
print('invalid input, case sensitive. Try again')
computerHand = random.choice(possibleHands)
print('your Hand: ', playerHand)
print('cpu Hand: ', computerHand)
results = checkForWinner(playerHand, computerHand)
if(results == 'player'):
playerScore += 1
elif(results == 'cpu'):
cpuScore += 1
else:
tieScore += 1
print('your score: ', playerScore, 'CPU: ', cpuScore, 'Ties: ', tieScore)
print('gg game over')
got this from a youtube tutorial
You must declare the function before its usage. On line 8 getRandomShape is called before its definition, so a NameError would occur.
What you can do is to put all the code that is not in a function, other than the import statements inside a main() function. And at the end you add:
if __name__ == ‘__main__’:
main()
When the program is called it would execute the main() function, and it would not matter if you put the function before or after others. The only thing that matters is you only call functions after they are already defined.
You can learn more about it here.
There are many more problems with this code, and this only fixes the NameError
that you are currently facing.

Inability to execute the call function within my main statement for rock, paper, scissors

Before anyone marks this question as a duplicate of anyone else's relating to this type of program, know that I searched and read the answered questions on this topic and was unable to find anything that suits my needs.
In my program for rock, paper, scissors I am asked to figure out if the computer or the player wins, or if they tie. We are supposed to store computer win as -1, player win as 1, and tie as 0. I thought I wrote this function correctly and called it properly in my main function, however, when I run my code it skips right over my runGame function and instead skips to an infinite loop asking the player to input their choice. I do not know why this is happening. I should note that within my main function, we are supposed to keep a counter to see how many wins the computer has and the player has, and how many times they tie. I also am having difficulty getting this to execute.
import random
# Function: Display Menu
# Input: none
# Output: none
# displays the game rules to the user
def displayMenu():
print("Welcome! Let's play rock, paper, scissors.")
print("The rules of the game are:")
print("\tRock smashes scissors")
print("\tScissors cut paper")
print("\tPaper covers rock")
print("\tIf both the choices are the same, it's a tie")
# Function: Get Computer Choice
# Input: none
# Output: integer that is randomly chosen, a number between 0 to 2
def getComputerChoice():
computerChoice = random.randrange(0,3)
return computerChoice
# Function: Get Player Choice
# Input: none
# Output: integer that represents the choice
# Asks the user for their choice: 0 for rock, 1 for paper, or 2 for scissors
def getPlayerChoice():
playerChoice = int(input("Please choose (0) for rock, (1) for paper or (2) for scissors"))
return playerChoice
# Function: Play Round
# Input: two integers--one representing the computer's choice and the other representing the player's choice
# Output: integer (-1 if computer wins, 1 if player wins, 0 if there is a tie)
# This method contains the game logic so it stimulates the game and determines a winner
def playRound(computerChoice, playerChoice):
if playerChoice == 0 and computerChoice == 2:
return 1
elif computerChoice == 0 and playerChoice == 2:
return -1
elif playerChoice == 2 and computerChoice == 1:
return 1
elif computerChoice == 2 and playerChoice == 1:
return -1
elif playerChoice == 1 and computerChoice == 0:
return 1
elif computerChoice == 1 and playerChoice == 0:
return 1
else:
return 0
# Function: Continue Game
# Input: none
# Output: boolean
# Ask the user is they want to continue (Y/N), and then return True or False accordingly
def continueGame():
playAgain = input("Do you want to continue playing? Enter (y) for yes or (n) for no.")
if playAgain.lower() == "y":
return True
elif playAgain.lower() == "n":
return False
# Function: main
# Input: none
# Output: none
def main():
playerCounter = 0
computerCounter = 0
tieCounter = 0
displayMenu()
p_choice = getPlayerChoice()
if p_choice == 0:
choicePlayer = "rock"
elif p_choice == 1:
choicePlayer = "paper"
elif p_choice == 2:
choicePlayer = "scissors"
getComputerChoice()
c_choice = getComputerChoice()
if c_choice == 0:
choiceComputer = "rock"
elif c_choice == 1:
choiceComputer = "paper"
elif c_choice == 2:
choiceComputer = "scissors"
print("You chose", choicePlayer + ".")
print("The computer chose", choiceComputer + ".")
playRound(getComputerChoice(), getPlayerChoice())
while playRound(c_choice, p_choice) == -1:
computerCounter += 1
while playRound(getPlayerChoice(), getPlayerChoice()) == 1:
playerCounter += 1
while playRound(getPlayerChoice(), getPlayerChoice()) == 0:
tieCounter += 1
continueGame()
while continueGame() == True:
displayMenu()
getPlayerChoice()
getComputerChoice()
playRound(getComputerChoice(), getPlayerChoice())
continueGame()
while continueGame() == False:
print()
print("You won", playerCounter, "game(s).")
print("The computer won", computerCounter, "game(s).")
print("You tied with the computer", tieCounter, "time(s).")
print()
print("Thanks for playing!")
# Call Main
main()
You don't have a "runGame" method, I believe you are referring to playRound.
In that case, once again, in this line:
playRound(getComputerChoice(), getPlayerChoice())
You are calling the getComputerChoice() and getPlayerChoice() methods again, and this is not what you want. Because of that it is asking you for the input again. You should do:
playRound(c_choice, p_choice)
There are some issues with your code. Firstly, you unnecessary call getComputerChoice(), getPlayerChoice() and continueGame() functions multiple times when it is not needed. Secondly, you have multiple weird while loops that don't do what you actually think they do.
Here is how you can modify your function in order to have a working program.
def main():
playerCounter = 0
computerCounter = 0
tieCounter = 0
displayMenu()
next_game = True
while next_game:
p_choice = getPlayerChoice()
if p_choice == 0:
choicePlayer = "rock"
elif p_choice == 1:
choicePlayer = "paper"
elif p_choice == 2:
choicePlayer = "scissors"
c_choice = getComputerChoice()
if c_choice == 0:
choiceComputer = "rock"
elif c_choice == 1:
choiceComputer = "paper"
elif c_choice == 2:
choiceComputer = "scissors"
print("You chose", choicePlayer + ".")
print("The computer chose", choiceComputer + ".")
result = playRound(p_choice, c_choice)
if result == -1:
computerCounter += 1
elif result == 0:
tieCounter += 1
else:
playerCounter += 1
next_game = continueGame()
print("You won", playerCounter, "game(s).")
print("The computer won", computerCounter, "game(s).")
print("You tied with the computer", tieCounter, "time(s).")
print()
print("Thanks for playing!")

rock paper scissors lizard spock, Python

I am creating a rock paper scissors lizard spock game in Python for my class and i am trying to figure out why whatever choice I make I am always winning even though I set up all my if statements correct. `
import random
def instructions():
play = input("Would you like to play Rock, Paper, Scissors, Lizard, Spock(y/n): ").lower()
if play == "y":
print("1.Rock")
print("2.Paper")
print("3.Scissors")
print("4.Lizard")
print("5.Spock")
elif play != "n":
print("error has accured please type y for yes or n for no:")
instructions()
def getPlayerChoice():
choice = int(input("What is your choice user?: "))
if choice > 5:
print("Invalid number please try again....")
getPlayerChoice()
elif choice < 1:
print("Invalid number please try again....")
getPlayerChoice()
elif choice == 1:
print("You picked Rock")
elif choice == 2:
print("You picked Paper")
elif choice == 3:
print("You picked Scissors")
elif choice == 4:
print("You picked Lizard")
elif choice == 5:
print("You picked Spock")
return choice
def getCPUChoice():
choice = random.randint(1,5)
if choice == 1:
print("CPU picked Rock")
elif choice == 2:
print("CPU picked Paper")
elif choice == 3:
print("CPU picked Scissors")
elif choice == 4:
print("CPU picked Lizard")
elif choice == 5:
print("CPU picked Spock")
return choice
def winner(playerChoice, CPUChoice, playerWins, CPUWins, ties):
if playerChoice == 1 and CPUChoice == 3 or CPUChoice == 4:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 2 and CPUChoice == 1 or CPUChoice == 5:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 3 and CPUChoice == 2 or CPUChoice == 4:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 4 and CPUChoice == 2 or CPUChoice == 5:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 5 and CPUChoice == 1 or CPUChoice == 3:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == CPUChoice:
print("Tie")
ties = ties.append(1)
else:
print("CPU won")
CPUWins = CPUWins.append(1)
return
def gameTotal(playerWins, CPUWins, ties):
playerWins = sum(playerWins)
CPUWins = sum(CPUWins)
ties = sum(ties)
print("Player final score: ", playerWins)
print("CPU final Score: ", CPUWins)
print("Total ties: ",ties)
def main():
playerChoice = 0
playerWins = []
CPUChoice = 0
CPUWins = []
ties = []
finalPlayerWins = 0
finalCPUWins = 0
finalTies = 0
Continue = 'y'
instructions()
while Continue == 'y':
playerChoice = getPlayerChoice()
CPUChoice = getCPUChoice()
winner(playerChoice,CPUChoice,playerWins, CPUWins, ties)
Continue = input("Would you like to play again (y/n):").lower()
if Continue == 'n':
print("Printing final scores.")
break
gameTotal(playerWins, CPUWins, ties)
main()
`
To summarize all of the things you should pay attention to:
boolean conditions - the result changes with the parentheses that are inside the condition.
if True or (True and False) --> this basically calculates the True and False part first (like in regular math) and then you have True or False which evaluates to True.
if True or True and False --> this basically calculates the True or True part first (like in regular math) and then you have True and False which evaluates to False - because you don't use parentheses.
Do not call a function within the same function - this is called recursion, and it's not relevant for what you need. Use a while loop, that runs as long as i.e. - you didn't get a proper choice input (while choice!='n' and choice!='y':).
Your instructions choice - the choice made by the user doesn't really change the flow of the game. the game starts also if the user entered no. You should add an exit statement in the instructions function.
The reason is you are missing parentheses on all of the "if" conditions.
if False and True or True # =True
if False and (True or False) # =False

A local or global name can not be found error [duplicate]

This question already has answers here:
Python NameError from contents of a variable
(2 answers)
Closed 8 years ago.
I'm trying to make a simple rock paper scissors game, and I get an error with in the line, guess = input. It says I need to define the function or variable before I use it in this way and I am unsure of how I can do that. This is using Python/JES programming
#import random module
import random
#main function
def main():
#intro message
print("Let's play 'Rock, Paper, Scissors'!")
#call the user's guess function
number = user_guess()
#call the computer's number function
num = computer_number()
#call the results function
results(num, number)
#computer_number function
def computer_number():
#get a random number in the range of 1 through 3
num = random.randrange(1,4)
#if/elif statement
if num == 1:
print("Computer chooses rock")
elif num == 2:
print("Computer chooses paper")
elif num == 3:
print("Computer chooses scissors")
#return the number
return num
#user_guess function
def user_guess():
guess = input ("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
#while guess == 'paper' or guess == 'rock' or guess == 'scissors':
if is_valid_guess(guess):
#if/elif statement
#assign 1 to rock
if guess == 'rock':
number = 1
#assign 2 to paper
elif guess == 'paper':
number = 2
#assign 3 to scissors
elif guess == 'scissors':
number = 3
return number
else:
print('That response is invalid.')
return user_guess()
def is_valid_guess(guess):
if guess == 'rock' or guess == 'paper' or guess == 'scissors':
status = True
else:
status = False
return status
def restart():
answer = input("Would you like to play again? Enter 'y' for yes or \
'n' for no: ")
#if/elif statement
if answer == 'y':
main()
elif answer == 'n':
print("Goodbye!")
else:
print("Please enter only 'y' or 'n'!")
#call restart
restart()
#results function
def results(num, number):
#find the difference in the two numbers
difference = num - number
#if/elif statement
if difference == 0:
print("TIE!")
#call restart
restart()
elif difference % 3 == 1:
print("I'm sorry! You lost :(")
#call restart
restart()
elif difference % 3 == 2:
print("Congratulations! You won :)")
#call restart
restart()
main()
Using raw_input instead of input seems to solve the problem.
guess = raw_input ("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
and also in
answer = raw_input("Would you like to play again? Enter 'y' for yes or 'n' for no: ")
I'm using Python 2.7.x

Categories