Value error when making a rock, paper, scissors game - python

I have just started programming in Python. I am currently trying to build a rock, paper, scissors game. The user is asked to pick a number representing one of the three options. Whereas the pc picks a random number. However, i get a value error for the input line. The same line worked fine in a different context (no while loop) but I fail to see what I did wrong. Any help would be greatly appreciated.
I have tried to turn the string into a float and then into an integer. That did not work. Moreover, I have replaced the player input number y a random number to test the rest of the code. This worked just fine.
This is the error message I get:
answerplayer = int (input('What is your choice? ')) #Error
ValueError: invalid literal for int() with base 10: "runfile
The code:
import random
win = False
while win == False:
print ('Rock, Paper, Scissors. 0: Rock; 1: Scissors; 2: Paper')
print ('Make your choice')
answerplayer = int (input('What is your choice? ')) #Error
answer = random.randrange (3)
print (answerplayer)
print (answer)
if answer == 0 and answerplayer == 0 :
print ('TIE')
elif answer == 0 and answerplayer == 1 :
print ('PC Win')
win = True
elif answer == 0 and answerplayer == 2 :
print ('Player Win')
win = True
elif answer == 1 and answerplayer == 0 :
print ('Player Win')
win = True
elif answer == 1 and answerplayer == 1 :
print ('TIE')
elif answer == 1 and answerplayer == 2 :
print ('PC Win')
win = True
elif answer == 2 and answerplayer == 0 :
print ('Player Win')
win = True
elif answer == 2 and answerplayer == 1 :
print ('PC Win')
win = True
elif answer == 2 and answerplayer == 2 :
print ('TIE')
else:
print ('Player Win')
win = True
print ('done')

The code is fine. User input must be something that int() can convert to integer however.
Passes: 1 2 3.444
Fails: sqfe zero

you can solve with:
while win == False:
print ('Rock, Paper, Scissors. 0: Rock; 1: Scissors; 2: Paper')
print ('Make your choice')
answerplayer = input('What is your choice? ')
if not answerplayer.isnumeric() :
print ('No number')
break
answerplayer = int(answerplayer)
answer = random.randrange (3)
print (answerplayer)
print (answer)

Related

A little confused about my issues with printing a string while inserting a score

I'm really new to Python and one of the things I'm struggling with is getting my code to run properly, I want it to print the current score every round but I'm having an issue adding the score into the string (Ideally not inline but if I have to I can do).
If anyone has any ideas, even if it's not specifically about the problem but instead just making the code overall more efficient, any help would be appreciated.
from random import randint
play = 1
while play == 1:
# Get user input & choose value
player, opponentInt = input("Rock, Paper, or Scissors? (r/p/s)\n"), randint(1,3)
player = player.lower()
# Assigning player input to int value
playerInt = []
if player == 'r':
playerStr, playerInt = 'Rock', 1
elif player == 'p':
playerStr, playerInt = 'Paper', 2
elif player == 's':
playerStr, playerInt = 'Scissors', 3
# Assigning randint function input to str value
if opponentInt == 1:
opponentStr = 'Rock'
elif opponentInt == 2:
opponentStr = 'Paper'
elif opponentInt == 3:
opponentStr = 'Scissors'
# Define strings
def winStr():
print("You chose {}, and I chose {}. Congratulations! You won! (Score = {})".format(player, opponentStr, score))
def loseStr():
print("You chose {}, and I chose {}. Unfortunately, you lost. (Score = {})".format(player, opponentStr, score))
def drawStr():
print("You chose {}, and I chose {}. It was a draw. (Score = {})".format(player, opponentStr, score))
# Give result of game
score = 0
if playerInt == []:
print('Unexpected value, please play again and check spellings.')
elif playerInt == 1 and opponentInt == 3:
score = score + 1
winStr()
elif playerInt == 3 and opponentInt == 1:
score = score - 1
loseStr()
elif playerInt > opponentInt:
score = score + 1
winStr()
elif playerInt < opponentInt:
score = score - 1
loseStr()
elif playerInt == opponentInt:
drawStr()
# Ask user if they would wish to play again
play = 2
while play == 2:
playAgain = input("Would you like to play again? (y/n) ")
playAgain = playAgain.lower()
if playAgain == 'y':
play = 1
elif playAgain == 'n':
play = 0
else:
play = 2
print("Unexpected value...")
# Print score
print("Your score was {}.".format(score))
Thanks for any help.
I have tried making strings using:
str = "String here. Score = {}".format(score)
Along with my latest:
def str():
print("String here. Score = {}".format(score))
str()
You should pass these variables as arguments to your functions
def print_str(score):
print("String here. Score = {}".format(score))
print_str(5)
As an aside you could use f-strings instead of str.format
def print_str(score):
print(f'String here. Score = {score}')
I have now fixed it and thank you to #CodyKramer for the tip in assigning formatting a string. Turned out I had an issue where the loop was resetting the variable I found after the string was actually printing the score change.
play = 1
while play == 1:
...
score = 0
if ...
score += 1
print(score)
...
Where in fact it should have been:
play = 1
score = 0
while play == 1:
...
if ...
score += 1
print(score)
...

My main function is repeating in an infinite loop and I do not know why

I am running a program that plays rock, paper, scissors. I have executed the code multiple times and everytime I do, the input asking the user to pick 0,1,2 repeats more than one time. It is only supposed to be asked one time per game cycle. Can anyone help me figure out why this is happening, and how to fix it?
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(getcomputerChoice, getplayerChoice):
if getplayerChoice == 0 and getcomputerChoice == 2:
return 1
elif getcomputerChoice == 0 and getplayerChoice == 2:
return -1
elif getplayerChoice == 2 and getcomputerChoice == 1:
return 1
elif getcomputerChoice == 2 and getplayerChoice == 1:
return -1
elif getplayerChoice == 1 and getcomputerChoice == 0:
return 1
elif getcomputerChoice == 1 and getplayerChoice == 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():
displayMenu()
getPlayerChoice()
if getPlayerChoice() == 0:
choicePlayer = "rock"
elif getPlayerChoice() == 1:
choicePlayer = "paper"
elif getPlayerChoice() == 2:
choicePlayer = "scissors"
getComputerChoice()
if getComputerChoice() == 0:
choiceComputer = "rock"
elif getComputerChoice() == 1:
choiceComputer = "paper"
elif getComputerChoice() == 2:
choiceComputer = "scissors"
print("You chose", choicePlayer + ".")
print("The computer chose", choiceComputer + ".")
playRound(getComputerChoice(), getPlayerChoice())
continueGame()
while continueGame() == True:
displayMenu()
getPlayerChoice()
getComputerChoice()
playRound(getComputerChoice(), getPlayerChoice())
continueGame()
playerCounter = 0
computerCounter = 0
tieCounter = 0
while playRound(getPlayerChoice(), getPlayerChoice()) == -1:
computerCounter += 1
while playRound(getPlayerChoice(), getPlayerChoice()) == 1:
playerCounter += 1
while playRound(getPlayerChoice(), getPlayerChoice()) == 0:
tieCounter += 1
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()
It's because when you do:
if getPlayerChoice() == 0:
choicePlayer = "rock"
You are actually calling the method again.
You should do:
p_choice = getPlayerChoice()
if p_choice == 0:
...

Rock paper scissors, skipping a result

import random
for i in range(3):
user = str(input("Please enter your choice: "))
if (random.randrange(3)) == 0 :
print("Computer chooses Rock")
if user == "scissors" :
print("computer wins")
elif user == "paper" :
print("player wins")
else :
print("tie")
elif (random.randrange(3)) == 1 :
print("Computer chooses Paper")
if user == "rock" :
print("computer wins")
elif user == "scissors" :
print("player wins")
else :
print("tie")
elif (random.randrange(3)) == 2 :
print("Computer chooses Scissors")
if user == "paper" :
print("computer wins")
elif user == "rock" :
print("player wins")
else :
print("tie")
The formatting is a bit weird on here (havent used this website before). I dont know the reason but i dont know why this code sometimes skips a result. if anyone could help that would be great.
This is what is produced when it is run a couple of times
enter your choice: scissors
Computer chooses Rock
computer wins
enter your choice: scissors
Computer chooses Scissors
tie
enter your choice: scissors
Computer chooses Rock
computer wins
================================ RESTART ================================
Please enter your choice: scissors
Please enter your choice: rock
Computer chooses Rock
tie
Please enter your choice: rock
Computer chooses Rock
tie
I dont understand why it skips a result. Seems to happen randomly
you should not use random.randrange(3) three times. This may e.g. give you the following numbers: 1, 2 and then 0. So the code which is then executed would be:
if (1 == 0):
...
elif (2 == 1):
...
elif (0 == 2):
...
and none of the conditional blocks of the if statements would be executed.
Instead do something like this:
computerChoice = random.randrange(3)
...
if computerCoice == 0:
...
elif computerChoice == 1:
...
elif computerChoice == 2:
...
else
raise Exception("something is definitively wrong here")
you have used random.randrange(3) multiple times and each time there is a possibility of it being a different number.. So i would suggest you assign the value to a variable and then use that in your if statements:
x = random.randrange(3)
I see that you've accepted the excellent answer of Andre, that takes you to understand clearly your error. As I commented your Q saying that there are simpler ways to award a hand, here it is my take
import random
c = random.randrange(3)
u = int(input('1=scissors, 2=paper, 3=rock: '))-1
if u==c:
print '... tie ...'
elif (u==0 and c==1) or (u==1 and c==2) or (u==2 and c==0):
print 'User wins!'
else:
print 'Computer wins... Booh!'
but I'm not sure if it is simpler... shorter for sure it is, but simpler?
One can make it even shorter
import random
def hand():
c = random.randrange(3)
u = int(input('1=scissors, 2=paper, 3=rock: '))-1
print "User played",['scissors,', 'paper,', 'rock,'][u],
print "computer played",['scissors.', 'paper.', 'rock.'][c]
print ['Tie.', 'User wins!', 'Computer wins...'][(c-u)%3]
This is an example session:
>>> hand()
1=scissors, 2=paper, 3=rock: 3
User played rock, computer played scissors.
User wins!
>>>
Yes, it is happening randomly. :)
if (random.randrange(3)) == 0 :
# computer "chooses" a random number
elif (random.randrange(3)) == 1 :
# now the computer's choice is a new choice from 0..2
elif (random.randrange(3)) == 2 :
# and now it's different again
Your mistake is here :
if (random.randrange(3)) == 0 :
elif (random.randrange(3)) == 1 :
elif (random.randrange(3)) == 2 :
In the if statement random.randrange(3) will generate a random number if it doesn't match, it will go to elif statement and random.randrange(3) will generate another random number and it may not be the same as the previously generated random number . Some time because of this your code will skip one , two , three or none of the statement .
If you want your code to be good , you should assign the random number to an integer and then use that integer in your answer .
It should be
ran=random.randrange(3)
if ran == 0 :
elif ran == 2 :
elif ran == 3 :

I don't understand why a NameError is thrown in my game

Code:
import random
score = 0
score2 = 0
guess = 0 #Defining Variables
quiz = 0
lives = 3
print('''Would you like to play a 'Guess the number' or a '3 round quiz'?
For Guess the number enter '1', for 3 round quiz enter '2' ''')
game = input()
if game == ("1"):
guess = guess + 1
print("Ok, time to start") #Asking what game you want to play
elif game == ("2"):
quiz = quiz + 1
else:
print("Please answer with 'Guess the number game' or a '3 round quiz'")
if quiz == 1:
print("Would you like to play 'Easy' or 'Hard'?")
difi = input()
if difi == ("Easy"):
print("Ok, let's go!") #Choosing difficulty
score = score + 1
elif difi == ("Hard"):
print("Ok,let's go")
score2 = score2 + 1
else:
print("Please answer with 'Easy' or 'Hard'")
if score == 1:
num1 = (random.randint(1, 50))
num2 = (random.randint(1, 50))
print("First question")
print("What is ",num1,"+",num2) # Question 1 easy
ans1 = input()
ans1 = int(ans1)
if ans1 == num1+num2:
print("Well done")
score = score + 1
else:
print("Unlucky, it was ",num1+num2)
if score == 2:
num3 = (random.randint(1, 10))
num4 = (random.randint(1, 10))
print("Next question")
print("What is ",num3,"*",num4) # Question 2 easy
ans2 = input()
ans2 = int(ans2)
if ans2 == num3*num4:
print("Congratualtions, on to the last question")
score = score + 1
else:
print("Unlucky, it was ",num3*num4)
if score == 3:
num5 = (random.randint(1, 5))
num6 = (random.randint(1, 2))
print("What is ",num5,"**(To the power of)",num6) # Question 3 easy
ans3 = input()
ans3 = int(ans3)
if ans3 == num5**num6:
print("Congratualtions, you beat the game on easy")
print("Now try hard!")
score = score + 1
else:
print("Unlucky, it was ",num5**num6)
if score == 4:
print("Would you like to try hard?")
hard2 = input()
else:
print("Ok, come back later") # If you beat easy you can choose to play hard here
if hard2 == ("Yes"):
print("This is the hard game, good luck!")
score2 = score2 + 1
elif hard2 == ("No"):
print("Ok, see you soon")
else:
print("Please answer with 'Yes' or 'No'")
if score2 == 1:
num12 = (random.randint(1, 500))
num22 = (random.randint(1, 500))
print("First question")
print("What is ",num12,"+",num22) # Question 1 hard
ans12 = input()
ans12 = int(ans12)
if ans12 == num12+num22:
print("Well done")
score2 = score2 + 1
else:
print("Unlucky, it was ",num1+num2) #2s in front of all hard variables so it differentiates the variables #From Easy and Hard
if score2 == 2:
num32 = (random.randint(1, 25))
num42 = (random.randint(1, 25))
print("Next question")
print("What is ",num32,"*",num42) # Question 2 hard
ans22 = input()
ans22 = int(ans22)
if ans22 == num32*num42:
print("Congratulations, on to the last question")
score2 = score2 + 1
else:
print("Unlucky, it was ",num32*num42)
if score2 == 3:
num52 = (random.randint(1, 15))
num62 = (random.randint(1, 3))
print("What is ",num52,"**(To the power of)",num62) # Question 3 hard
ans32 = input()
ans32 = int(ans32)
if ans32 == num52**num62:
print("Congratualtions, you beat the game on hard")
else:
print("Unlucky, it was ",num52**num62)
if guess == 1:
print("Time to play") #Guess the number game
guess = guess + 1
if guess == 2:
print("Pick a number between 1 an 10")
comp_num = (random.randint(1,10))
user_guess1 = input()
user_guess1 = int(user_guess1)
if user_guess1 == comp_num:
print("Well done, you beat the game on your first turn!")
else:
print("Unlucky you still have 2 more goes")
lives = lives - 1
if lives == 2:
print("Guess again")
user_guess2 = input()
user_guess2 = int(user_guess2)
if user_guess2 == comp_num:
print("Congrats, you beat it on your second guess!")
lives = lives - 1
if lives == 1:
print("Guess again")
user_guess3 = input()
user_guess3 = int(user_guess3)
if user_guess3 == comp_num:
print("Congrats, you beat it on your last life!")
lives = lives - 1
else:
print("Unlucky, care to try again")
if lives == 0:
retry = input()
if retry == ("Yes"):
lives = lives + 3
elif retry == ("No"):
print("Ok, come back soon")
else:
print("Please answer with 'Yes' or 'No'")
Error:
Traceback (most recent call last):
File "C:\Users\Boys\Desktop\3 Round Quiz.py", line 24, in <module>
if difi == ("Easy"):
NameError: name 'difi' is not defined
The error above comes up when I enter '1' to play the game 'Guess the number' it comes up with that, even though the variable difi is for the quiz. I'm not sure why this happens so any help will be appreciated!
Thanks
difi is only ever bound if quiz is 1:
if quiz == 1:
print("Would you like to play 'Easy' or 'Hard'?")
difi = input()
You don't set difi otherwise, and the name is not defined in that case.
quiz starts at 0, and isn't incremented unless you pick '2':
elif game == ("2"):
quiz = quiz + 1
If you pick '1', on the other hand, quiz remains at 0, difi is not set, and your code breaks.
The control flow is reaching the if difi == ("Easy"): line before difi is defined because quiz is still 0 at the top. I suspect you intended the if difi == ("Easy"): and associated parts of the code to be indented more so they appear inside the if quiz == 1: block.

Rock Paper Scissors function help in Python

I just started learning Python, and I am trying to write a basic Rock Paper Scissors program for my assignment. The game is intended to go on for 10 rounds, while keeping track the score between the player and the computer. I have two specific problems with it.
import random
def welcome_prompt():
print ("ROCKER PAPER SCISSORS in PYTHON Assignment")
print ("Rules: Rocks beats Scissors, Scissors beats Paper, Paper beats Rock")
def get_player_move():
print ('Round ' + str(round))
print ("Please play one of the following")
get_player_move = raw_input(" 1) [R]ock, 2) [P]aper, 3) [S]cissors:")
if get_player_move == ("R"):
print ("You used Rock!")
return 1
elif get_player_move == ("P"):
print ("You used Paper!")
return 2
elif get_player_move == ("S"):
print ("You used Scissors!")
return 3
else:
print "Invalid input, please use capitalized initial (R,P,S)"
return get_player_move()
def get_computer_move():
get_computer_move = random.randint(1,3)
if get_computer_move == 1:
print ("Computer used Rock!")
return 1
elif get_computer_move == 2:
print ("Computer used Paper!")
return 2
elif get_computer_move == 3:
print ("Computer used Scissors!")
return 3
def compare_moves(get_player_move, get_computer_move):
# Rock = 1
# Paper = 2
# Scissors = 3
if (get_player_move == 1 and get_computer_move == 1) or (get_player_move == 2 and get_computer_move == 2) or (get_player_move == 3 and get_computer_move == 3):
print ("It's a tie!")
return 0
elif (get_player_move == 1 and get_computer_move == 3) or (get_player_move == 2 and get_computer_move == 1) or (get_player_move == 3 and get_computer_move == 2):
print ("You win the round!")
return 1
elif (get_player_move == 1 and get_computer_move == 2) or (get_player_move == 2 and get_computer_move == 3) or (get_player_move == 3 and get_computer_move == 1):
print ("You lose the round!")
return -1
elif (get_player_move == 4):
print ("You didn't put in correct input, computer gets a free win")
return -1
# Game Program
player_score = 0
comp_score = 0
round = 0
welcome_prompt()
('Round ' + str(round))
while round< 10:
round = round + 1
get_player_move()
get_computer_move()
compare_moves(get_player_move, get_computer_move)
if compare_moves == 1:
player_score = player_score + 1
print 'Player Score'+ str(player_score)
print 'Computer Score'+ str(player_score)
elif compare_moves == -1:
comp_score = comp_score + 1
print 'Player Score'+ str(player_score)
print 'Computer Score'+ str(player_score)
print "Game Over"
Firstly, I can't get the compare_move function to recall the returned values from both get_player_move and get_computer_move. The game can run without any error, but it just skips the comparison/ score component completely. I am still a bit iffy with the basics, so not exactly sure what is missing.
Secondly, in the get_player_move function, when I enter an invalid input (example: blah) to test the raw_input, it gives an error.
Traceback (most recent call last):
File "C:\Python27\Rock Paper Scissors.py", line 85, in <module>
get_player_move()
File "C:\Python27\Rock Paper Scissors.py", line 32, in get_player_move
return get_player_move()
TypeError: 'str' object is not callable
So how do you make a function to asks for the correct raw_input again after entering invalid input, without interrupting the while loop?
Explanation is greatly appreciated, thank you
You have a local variable get_player_move inside the function get_player_move(); you cannot then still use the function name (a global).
Rename the get_player_move local variable.
So, instead of:
get_player_move = raw_input(" 1) [R]ock, 2) [P]aper, 3) [S]cissors:")
use:
move = raw_input(" 1) [R]ock, 2) [P]aper, 3) [S]cissors:")
perhaps.
To get user input, it's best not to rely on recursion, however. The user could hit 'C' forever and then your program would crash with an RuntimeError: maximum recursion depth exceeded. It's easier to use a loop instead:
while True:
move = raw_input(" 1) [R]ock, 2) [P]aper, 3) [S]cissors:")
if move == "R":
print ("You used Rock!")
return 1
# etc.
else:
print "Invalid input, please use capitalized initial (R,P,S)"
Because you return from the function when a correct choice is made, the loop automatically is exited as well. If however you get to the end and Invalid input is printed, the while True loop starts at the top again and the user is asked once more to enter a choice.
Next: although your function returns a choice (an integer), you never store that return value. You must store it where you called the function:
player_move = get_player_move()
computer_move = get_computer_move()
result = compare_moves(player_move, computer_move)
if result == 1:
Note that it's not the function name that holds the return value; it's a separate variable. player_move is assigned whatever the get_player_move() returned, for example.
You can then pass these returned values to compare_moves(); it also returns a result, here stored in result for further comparisons.

Categories

Resources