I am making rock paper scissors and when I run it it says "Can't convert 'int' object to str implicitly".
import time
import random
print("Do you want to play rock, paper, scissors?")
playerscore = 0
cpuscore = 0
game = input()
game = game.upper()
while game == "SURE" or game == "YES" or game == "YEAH": # starts rock paper scissors
number = random.randint(1, 3)
if number == 1:
cpurpors = "SCISSORS"
elif number == 2:
cpurpors = "ROCK"
elif number == 3:
cpurpors = "PAPER"
print("Cool! Rock, paper or scissors?")
rpors = input()
rpors = rpors.upper()
print("Rock")
time.sleep(.5)
print("Paper")
time.sleep(.5)
print("Scissors")
time.sleep(.5)
print(cpurpors + "!")
time.sleep(.5)
if cpurpors == rpors:
print("Draw!")
elif cpurpors == "SCISSORS" and rpors == "PAPER" or cpurpors == "PAPER" and rpors == "ROCK" or cpurpors == "ROCK" and rpors == "SCISSORS":
cpuscore = cpuscore + 1
print("Haha, I win!")
elif rpors == "SCISSORS" and cpurpors == "PAPER" or rpors == "PAPER" and cpurpors == "ROCK" or rpors == "ROCK" and cpurpors == "SCISSORS":
playerscore = playerscore + 1
print("Oh no! You win!")
print("The scores are:")
print("Guiseppebot: " + cpuscore)
print(name + ": " + playerscore)
print("Would you like to play again?")
game = input()
game = game.upper()
The problem is that you're adding int variables to the print statements. Try doing something like this:
print(name + ": " + str(playerscore))
In that example, you're setting playerscore to the string version of the int.
Need to wrap the integers cpuscore and playerscore with str to convert them to a string, as it won't do it implicitly.
print("Guiseppebot: " + str(cpuscore))
print(name + ": " + str(playerscore))
Another nice option is using format, which does call str on objects for you so you don't have to worry about it in the future:
print("Guiseppebot: {}".format(cpuscore))
print("{}: {}".format(name, playerscore))
str is the built-in function that will convert non string objects to a string. It does this by calling the objects .__str__ method if it exists (and knows how to otherwise for objects like ints and floats.) Read more about it in the docs here https://docs.python.org/3/library/stdtypes.html#str
I'm nor sure if this is the best solution, but my approach would be to use str() to convert the integer (cpuscore) to a string.
import time
import random
name = input ("what's your name? ") #added in input for variable (name)
print("Do you want to play rock, paper, scissors?")
playerscore = 0
cpuscore = 0
game = input()
game = game.upper()
while game == "SURE" or game == "YES" or game == "YEAH": # starts rock paper scissors
number = random.randint(1, 3)
if number == 1:
cpurpors = "SCISSORS"
elif number == 2:
cpurpors = "ROCK"
elif number == 3:
cpurpors = "PAPER"
print("Cool! Rock, paper or scissors?")
rpors = input()
rpors = rpors.upper()
print("Rock")
time.sleep(.5)
print("Paper")
time.sleep(.5)
print("Scissors")
time.sleep(.5)
print(cpurpors + "!")
time.sleep(.5)
if cpurpors == rpors:
print("Draw!")
elif cpurpors == "SCISSORS" and rpors == "PAPER" or cpurpors == "PAPER" and rpors == "ROCK" or cpurpors == "ROCK" and rpors == "SCISSORS":
cpuscore = cpuscore + 1
print("Haha, I win!")
elif rpors == "SCISSORS" and cpurpors == "PAPER" or rpors == "PAPER" and cpurpors == "ROCK" or rpors == "ROCK" and cpurpors == "SCISSORS":
playerscore = playerscore + 1
print("Oh no! You win!")
print("The scores are:")
print("Guiseppebot: " + str(cpuscore)) #converted cpuscore to a string
print(name + ": " + str(playerscore)) #variable (name) wasn't declared
print("Would you like to play again?")
game = input()
game = game.upper()
cpuscore is an integer(int) it can't be concatenated with a string. Python doesn't convert it to a string automatically("implicitly"). So you at least need to do:
print("Guiseppebot: " + str(cpuscore))
Even better/easier, in Python 3.6+, use f-strings
Assuming you can put the value inside a variable into a string (integers, strings, lists, dictionaries are ok), you just put them inside curly brackets.
Here's how the line with that error looks with f-strings:
print(f"Guiseppebot: {cpuscore}")
Related
I am writing a simple game of rock, paper and scissors, where the user competes with a computer. There are 5 tries.
The problems I ran into are :
If I enter something apart from three options, it should return "Invalid Entry". Instead, the program stops
The program never prints "You won the game" or "You lost the game", it finishes after 5 attempts
Other feedback would also be appreciated
import random
def game():
win_count = 0
loose_count = 0
tries = 0
while tries < 5:
chosen = input("Make your choice: ")
if chosen == "scissors" or chosen == "Scissors":
element = "scissors"
elif chosen == "paper" or chosen == "Paper":
element = "paper"
elif chosen == "rock" or chosen == "Rock":
element = "rock"
else:
return "Invalid Entry"
computer_choices = ["scissors", "paper", "rock"]
computer_choice = random.choice(computer_choices)
if element == "scissors" and computer_choice == "paper":
print("Computer chose paper, you chose scissors, you win !")
win_count += 1
tries += 1
elif element == "paper" and computer_choice == "scissors":
print("Computer chose scissors, you chose paper, you loose !")
loose_count += 1
tries += 1
elif element == "paper" and computer_choice == "rock":
print("Computer chose rock, you chose paper, you win !")
win_count += 1
tries += 1
elif element == "rock" and computer_choice == "paper":
print("Computer chose paper, you chose rock, you loose !")
loose_count += 1
tries += 1
else:
print("Whoops, that's a draw, try again")
tries+=1
print("Your Wins: "+ str(win_count))
print("Computer Wins: "+str(loose_count))
if win_count > loose_count:
return "Congrats, you won the game!"
else:
return "Sorry, you lost"
game()
return statement does not print anything but they return the value from a function and as soon as a return statement executes the function ends up executing that's why whenever the user inputs something invalid the program stop.
Also not use the if statement from if chosen = paper or chosen = Paper instead use .lower() to lower the string.
I have made some changes to your code.
Try this code
import random
def game():
win_count = 0
loose_count = 0
tries = 0
while tries < 5:
element = input("Make your choice: ").lower()
computer_choices = ["scissors", "paper", "rock"]
if element not in computer_choices:
print("Invalid choice")
continue
computer_choice = random.choice(computer_choices)
if element == "scissors" and computer_choice == "paper":
print("Computer chose paper, you chose scissors, you win !")
win_count += 1
tries += 1
elif element == "paper" and computer_choice == "scissors":
print("Computer chose scissors, you chose paper, you loose !")
loose_count += 1
tries += 1
elif element == "paper" and computer_choice == "rock":
print("Computer chose rock, you chose paper, you win !")
win_count += 1
tries += 1
elif element == "rock" and computer_choice == "paper":
print("Computer chose paper, you chose rock, you loose !")
loose_count += 1
tries += 1
else:
print("Whoops, that's a draw, try again")
tries+=1
print("Your Wins: "+ str(win_count))
print("Computer Wins: "+str(loose_count))
if win_count > loose_count:
print("Congrats, you won the game!")
else:
print("Sorry, you lost")
game()
I have written logic in python for the game of rock, paper , scissor but having trouble to get it to run.
It wont run the through the entire game and just keeps asking me for my input. I have looked through it multiple times but cant see where it might be getting stuck.
Any idea what the issue may be?
Code is as below:
import random
comp_wins = 0
player_wins = 0
def choose_option ():
user_choice = input("choose rock, paper and scissors: ")
if user_choice in ["rock","Rock"]:
user_choice = "rock"
elif user_choice in ["paper","Paper"]:
user_choice = "paper"
elif user_choice in ["scissors","Scissor"]:
user_choice = "scissors"
else:
print ("error try again")
return user_choice
def computer_option ():
comp_choice = random.randint(1,3)
if comp_choice ==1:
comp_choice = "rock"
elif comp_choice ==2:
comp_choice = "paper"
elif comp_choice ==3:
comp_choice = "scissors"
return comp_choice
while True:
print("")
user_choice = choose_option ()
comp_choice = computer_option ()
print ("")
if user_choice ==["rock"]:
if comp_choice == "rock":
print("draw")
elif comp_choice == "paper":
print("computer wins")
comp_wins += 1
elif comp_choice == "scissors":
print("user wins")
player_wins += 1
elif user_choice == "paper":
if comp_choice == "rock":
print("user wins")
player_wins += 1
elif comp_choice == "paper":
print("draw")
elif comp_choice == "scissors":
print("computer wins")
comp_wins += 1
elif user_choice == "scissors":
if comp_choice == "rock":
print("computer wins")
comp_wins += 1
elif comp_choice == "paper":
print("user wins")
player_wins += 1
elif comp_choice == "scissors":
print("draw")
print("")
print("user_wins: " + str(player_wins))
print("comp_wins: " + str(comp_wins))
print("")
Youur issue is here
while True:
print("")
user_choice = choose_option ()
comp_choice = computer_option ()
print ("")
You never exit this while, you should put an exit condition or a flag when a choice has been made.
Also it would be better to clean up and use a Top-Down structure with a main function in which you control the file.
It looks that there is a wrong indent: the main while True loop never ends. Try to move all blocks after this loop to the right (i.e. add four spaces in the beginning of all next lines).
Your indentation levels aren't correct. The if user_choice ==["rock"]: part is the same indentation level as the while statement, so it isn't included in the loop. You need to indent it to let Python know it's part of the loop block. And since you don't have anything that ends the loop, it will go on forever. Also, using strings to represent choices is really inefficient. If you represent choices with numbers, you can use modular arithmetic.
It's my first time here and I'm kinda panicking. I have an assignment to code Rock, Paper, Scissors in Python. (I use Python 3.1) and for some reason the function is not running...?
Here's the code:
hscore = 0
cscore = 0
tries = 0
#computer choice
rock = ("rock")
paper = ("paper")
scissors = ("scissors")
rps = (rock, paper, scissors)
cchoice = random.choice(rps)
choice = input("\nWhat do you choose? <rock, paper, scissors>: ")
tries +=1
def humanfunction():
if choice == "rock":
if cchoice == scissors:
print("Human wins this round.")
hscore +=1
if choice == "scissors":
if cchoice == paper:
print("Human wins this round.")
hscore +=1
if choice == "paper":
if cchoice == rock:
print("Human wins this round.")
hscore +=1
if cchoice == choice:
print("Tie.")
def compfunction():
if cchoice == scissors:
if choice == "paper":
print("Computer wins this round.")
cscore +=1
if cchoice == rock:
if choice == "scissors":
print("Computer wins this round.")
cscore +=1
if cchoice == paper:
if choice == "rock":
print("Computer wins this rounud.")
cscore +=1
if cchoice == choice:
print("Tie.")
def choose():
tries = 0
while 0 == 0:
choice = input("\nWhat do you choose? <rock, paper, scissors>: ")
tries +=1
print("\nHuman choice: ", choice)
print("Computer choice: ", cchoice)
print("Finished game number", tries)
if tries == 10:
print("Limit reached!")
break
humanfunction()
compfunction()
choose()
I've been trying to solve this for days now and for some reason, when I run the code, it doesn't show up who won. Help would be appreciated <3
EDIT:
here's what i get when i run the code:
output
the program is actually supposed to show this:
output2
Here is my take on your code.
The main reason it wasn't running is that your cscore variable was being referenced before it was initialized, because you had setup cscore as a global variable, but didn't declare it as a global variable in your function.
You also needed to import the random library
Also instead of doing 4 if/then statements I combined them into 1 if/then statement
EDIT: cleaned up the code a little more
EDIT 2: no more globals, avoid globals if possible
import random
def get_human_choice():
valid_choice = False
while not valid_choice:
choice = input("\nWhat do you choose? <rock, paper, scissors>: ")
if choice == 'rock' or 'paper' or 'scissors':
valid_choice = True
return choice
def get_comp_choice():
rps = ('rock', 'paper', 'scissors')
comp_choice = random.choice(rps)
return comp_choice
def human_winner(comp_choice):
print("The computer chooses: %s" % comp_choice)
print("Human wins this round.")
def comp_winner(comp_choice):
print("The computer chooses: %s" % comp_choice)
print("Computer wins this round.")
def stats(attempts, human_score, comp_scored, tie_score):
print("Finished game number: %s" % attempts)
print('Human Score: %s' % human_score)
print('Computer Score: %s' % comp_scored)
print('Ties: %s' % tie_score)
def play_game(human_score, comp_score, tie_score):
choice = get_human_choice()
comp_choice = get_comp_choice()
if choice == 'rock':
if comp_choice == 'scissors':
human_winner(comp_choice)
human_score += 1
else:
comp_winner(comp_choice)
comp_score += 1
elif choice == 'scissors':
if comp_choice == 'paper':
human_winner(comp_choice)
human_score += 1
else:
comp_winner(comp_choice)
comp_score += 1
elif choice == 'paper':
if comp_choice == 'rock':
human_winner(comp_choice)
human_score += 1
else:
comp_winner(comp_choice)
comp_score += 1
elif choice == comp_choice:
print("Tie.")
tie_score += 1
return human_score, comp_score, tie_score
if __name__ == '__main__':
tries = 1
h_score, c_score, t_score = 0, 0, 0
while tries <= 10:
h_score, c_score, t_score = play_game(h_score, c_score, t_score)
if tries == 10:
print("\nLimit reached!\n")
stats(tries, h_score, c_score, t_score)
break
else:
tries += 1
I made a simple Rock Paper Scissors program, and I need to add a certain condition to this program.. I have to Let the
user play continuously until either the user or the computer wins more than two times in a row.I tried to find the answer in and out but unfortunately couldn't find it..
First off I tried
gameOver = False
playerScore = 0
computerScore = 0
and added
while not gameOver:
main()
if playerScore == 2 :
gameOver = True
and also added playerScore += 1 to the if statements..
But wouldn't work ...
any advise would help and much appreciated in advance.. cheers!
And here is my code..
import random
import sys
def main():
player = input("Enter your choice in number (rock 1 / paper 2 / scissors 0) :")
if (player == 0):
player = "scissors"
elif (player == 1):
player = "rock"
elif (player == 2):
player = "paper"
else:
print("Invalid Input Quitting...")
sys.exit(0)
computer = random.randint(0,2)
if (computer == 0):
computer = "scissors"
elif (computer == 1):
computer = "rock"
elif (computer == 2):
computer = "paper"
if (player == computer):
print("Player is ",player, "Computer is ",computer," You Draw!")
elif (player == "rock"):
if (computer == "paper"):
print("Player is ",player, "Computer is ",computer," You Lost!")
else:
print("Player is ",player, "Computer is ",computer," You Win!")
elif (player == "paper"):
if (computer == "rock"):
print("Player is ",player, "Computer is ",computer," You Win!")
else:
print("Player is ",player, "Computer is ",computer," You Lost!")
elif (player == "scissors"):
if (computer == "rock"):
print("Player is ",player, "Computer is ",computer," You Lost!")
else:
print("Player is ",player, "Computer is ",computer," You Win!")
If you have your main() function return a value corresponding to who won, you could do:
gameOver = False
playerScore = 0
computerScore = 0
while not gameOver:
player_wins = main()
if player_wins == True:
playerScore += 1
computerScore = 0
if player_wins == False:
playerScore = 0
computerScore += 1
if player_wins == None:
# Draw, do nothing to the scores
pass
if playerScore == 2 or computerScore == 2:
print("Game over")
print(" playerScore:", playerScore)
print(" computerScore:", computerScore)
gameOver = True
Note that I had it return True if the player won, False if the computer won, and None if it was a draw.
I think you are asking only a schema:
(this is no true code)
Program starts:
gameover = False
lastWinner = ""
Loop until gameover == True
ask for player answer
make the random choice of the computer
winner = "asigned winner"
if lastWinner == winner:
gameover = True
Print something cool about who is the winner
else:
lastWinner = winner
You may be getting an error when attempting to modify the globals, but from your example it's not entirely clear.
If you try to modify playerScore or computerScore in your main() method, it'll yell at you unless you have a statement like:
global computerScore
before you modify it.
Also, avoid repeating yourself in your code. I was able to trim much of your code out by using the following:
computerWins = False
print "Player is %s; Computer is %s" % (computer, player)
if (player == computer):
print "Draw"
return 0
elif (player == "rock"):
computerWins = computer == "paper"
elif (player == "paper"):
computerWins = computer == "scissors"
elif (player == "scissors"):
computerWins = computer == "rock"
if computerWins:
global computerScore
computerScore = computerScore + 1
print "Computer wins"
else:
global playerScore
playerScore = playerScore + 1
print "You win"
I'm trying to write a Rock, Paper Scissors program with Python but I keep getting this error and I'm not sure how to fix it.
File "C:\Python33\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 140, in <module>
File "C:\Python33\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 34, in main
builtins.TypeError: 'tuple' object is not callable
This is my program:
import random
def main():
win = 0
lose = 0
tie = 0
ROCK_CHOICE = '1'
PAPER_CHOICE = '2'
SCISSORS_CHOICE = '3'
QUIT_CHOICE = '4'
play_again = 'y'
while play_again == 'y':
print('Welcome to the game of paper, rock, scissors!')
print('Please input the correct number according')
print('to the choices given.')
computer_choice = get_computer_choice()
player_choice = get_player_choice()
determine_winner = (computer_choice, player_choice)
print('Computer choose', computer_choice, '.')
print('You choose', player_choice, '.')
determine_winner(computer_choice, player_choice)
if result == -1:
lose += 1
elif result == 0:
tie += 1
else:
win += 1
play_again = input('Play again? Enter y for yes')
def get_computer_choice():
choice = random.randint(1,4)
if choice == 1:
choice = 'ROCK'
elif choice == 2:
choice = 'PAPER'
elif choice == 3:
choice = 'SCISSORS'
else:
choice = 4
return choice
def get_player_choice():
choice = int(input('Select rock(1), paper(2), or scissors(3): '))
while choice != 1 and choice != 2 and choice != 3:
print('The valid numbers are rock choice 1), paper choice 2),')
print('or scissors choice 3).')
choice = int(input('Please a valid number: '))
if choice == 1:
choice = 'ROCK'
elif choice == 2:
choice = 'PAPER'
elif choice == 3:
choice = 'SCISSORS'
else:
choice = 4
return choice
def determine_winner(computer_choice, player_choice):
if player_choice == ROCK_CHOICE and computer_choice == ROCK_CHOICE:
print('Its a tie.')
return 0
elif player_choice == PAPER_CHOICE and computer_choice == PAPER_CHOICE:
print('Its a tie.')
return 0
elif player_choice == SCISSORS_CHOICE and computer_choice == SCISSORS_CHOICE:
print('Its a tie.')
return 0
elif player_choice == ROCK_CHOICE and computer_choice == PAPER_CHOICE:
print('You lose, Rock covers Paper.')
return -1
elif player_choice == ROCK_CHOICE and computer_choice == SCISSORS_CHOICE:
print('You WIN!!! Rock smashes Scissors.')
return 1
elif player_choice == PAPER_CHOICE and computer_choice == SCISSORS_CHOICE:
print('You lose, Scissors cuts Paper.')
return -1
elif player_choice == SCISSORS_CHOICE and computer_choice == ROCK_CHOICE:
print('You lose, Rock smashes Paper.')
return -1
elif player_choice == SCISSORS_CHOICE and computer_choice == PAPER_CHOICE:
print('You WIN!!! Scissors cuts Paper.')
return 1
elif player_choice == PAPER_CHOICE and computer_choice == ROCK_CHOICE:
print('You WIN!!! Paper covers Rock.')
return 1
else:
player_choice == QUIT_CHOICE
print('Exiting the program...')
return
def display_results():
print()
print(' MENU')
print('1) Rock')
print('2) Paper')
print('3) Scissors')
print('4) Quit')
player_choice = input('Enter your choice:')
while player_choice != '1' and player_choice != '2' and \
player_choice != '3' and player_choice != '4':
print()
print('Error: invalid selection.')
player_choice = input('Please re-enter your choice:')
print('Your total wins are', win, '.')
print('Your total losses are', lose, '.')
print('Your total ties are', tie, '.')
main()
input('\nPress ENTER to continue...')
error 1:
fix line27 : result = determine_winner(computer_choice, player_choice
error 2:
if player_choice == ROCK_CHOICE and computer_choice == ROCK_CHOICE:
NameError: global name 'ROCK_CHOICE' is not defined
move:
ROCK_CHOICE = '1'
PAPER_CHOICE = '2'
SCISSORS_CHOICE = '3'
QUIT_CHOICE = '4'
outside main (to line 3)
error 3:
File "main.py", line 41, in main
play_again = input('Play again? Enter y for yes')
File "<string>", line 1, in <module>
NameError: name 'y' is not defined
input should be raw_input line 41:
play_again = raw_input('Play again? Enter y for yes')
NB. and the input('\nPress ENTER to continue...') also needs to be a raw_input
NNBB. and if you plan to use display_results; there is errors in there too.
from random import randint
class RPS:
def __init__(self, pCh):
self.playChoice = pCh
self.compChoice = ""
self.choice = randint(0, 3)
self.winner = ""
self.uCompChoice = ""
self.uPlayChoice = ""
if self.choice == 0:
self.compChoice = "R"
elif self.choice == 1:
self.compChoice = "P"
else:
self.compChoice = "S"
if self.compChoice == "R":
self.uCompChoice = "Rock"
if self.compChoice == "P":
self.uCompChoice = "Paper"
if self.compChoice == "S":
self.uCompChoice = "Scissors"
if self.playChoice == "P" or self.playChoice == "p" or self.playChoice == "Paper" or self.playChoice == "paper" or self.playChoice == "PAPER" or self.playChoice == "2":
self.uPlayChoice = "Paper"
if self.playChoice == "S" or self.playChoice == "s" or self.playChoice == "Scissors" or self.playChoice == "scissors" or self.playChoice == "SCISSORS" or self.playChoice == "3":
self.uPlayChoice = "Scissors"
if self.playChoice == "R" or self.playChoice == "r" or self.playChoice == "Rock" or self.playChoice == "rock" or self.playChoice == "ROCK" or self.playChoice == "1":
self.uPlayChoice = "Rock"
def determineWinner(self):
if self.uCompChoice == self.uPlayChoice:
return "Draw Game!"
elif self.uCompChoice == "Rock":
if self.uPlayChoice == "Paper":
return "You won because Paper covers Rock!!"
else:
return "Computer wins because Rock breaks Scissors."
elif self.uCompChoice == "Paper":
if self.uPlayChoice == "Scissors":
return "You won because Rock cuts Paper!!"
else:
return "Computer wins because Paper covers Rock."
else:
if self.uPlayChoice == "Rock":
return "You won because Rock breaks Scissors!!"
else:
return "Computer wins because Scissors cuts Paper."
def __str__(self):
return "Your weapon: " + self.uPlayChoice + "\n" + "Computer's weapon " + self.uCompChoice + "\n" + \
self.determineWinner()
def main():
print("Welcome to RockPaperScissors.")
print("Pick your weapon: ")
print("1. Rock")
print("2. Paper")
print("3. Scissors")
print("Note: If you don't pick a valid weapon the computer will pick a random weapon for you")
# input from user (weapon)
weapon = input("")
# Creating a new object
attack = RPS(weapon)
# printing the result
print(attack.__str__())
# Asking the user if he wants to play again
playagain = input("Would you like to play again: \n")
if playagain == "Yes" or playagain == "yes" or playagain == "YES" or playagain == "y" or playagain == "Y":
main()
else:
print("Thank you for playing.")
main()
don't you think, this code will be shorter this way:
print("R for rock")
print("P for paper")
print("S for scissors")
choices = ["rock", "paper", "scissor"]
while True:
choice = random.choice(choices)
player_choice = input("choose> ")
if player_choice.lower() == "r":
if choice == "rock":
print("i picked rock too!")
elif choice == 'paper':
print("YOU LOST! i picked paper")
else:
print("fine, you win")
elif player_choice.lower() == "p":
if choice == "rock":
print("You win.... Whatever!")
elif choice == 'paper':
print("haha same decisions")
else:
print("I won! You should be ashamed of losing against a bot")
elif player_choice.lower() == "s":
if choice == "rock":
print("I won! Humanity will soon be controlled by bots")
elif choice == 'paper':
print("Alright, you win")
else:
print("Draw")
else:
print("YOU WANNA PLAY GAMES WITH ME!??!?!?")