Rock, Papers and Scissors in Python - python

(I am new to python, please don't judge the quality of the code right now.)
So, I am making a program which let's you play rock, papers and scissors with the code. This is my code:
import random
name = str(input("Enter your name:\n"))
choices = ["rock", "papers", "scissors"]
print(f"Hi {name}, choose between rock, papers and scissors")
while True:
user_choice = str(input('> '))
user_choice.lower()
if user_choice not in choices:
print("ERROR")
computer_choice = random.choice(choices)
print(f"Computer chooses: {computer_choice}")
if user_choice == "rock":
if computer_choice == "papers":
print("Computer wins!")
elif computer_choice == "scissors":
print(f"{name} wins!")
if user_choice == "papers":
if computer_choice == "scissors":
print("Computer wins!")
if computer_choice == "rock":
print(f"{name} wins!")
if user_choice == "scissors":
if computer_choice == "rock":
print("Computer wins!")
elif computer_choice == "papers":
print(f"{name} wins!")
if user_choice == computer_choice:
print("Tie!")
But, like when I run the code, it is working out really good. However, the problem is that if the user does not enter the correct spelling, the output looks really messed up. Like this:
Enter your name:
_____
Hi _____, choose between rock, papers and scissors
> asdf
ERROR
Computer chooses: rock
I do not want the last line, the one which says "Computer chooses: rock". Please someone suggest how do I go about this.
Thanks in advance 🙏
(EDIT: Also, if you can suggest how I can include a point system in this, which calculates how many times the computer wins, the user wins and how many times the match was a tie, the effort would be really appreciated.)

Just use continue to force the user to enter a valid choice:
while True:
user_choice = str(input('> '))
user_choice = user_choice.lower()
if user_choice not in choices:
print(f"You chose {user_choice}, please choose rock, paper, or scissors")
continue
[...]

Looks like your error problem has already been solved : )
But for the tie and score counter I have prepared the following code-
import random
name = str(input("Enter your name:\n"))
choices = ["rock", "papers", "scissors"]
print(f"Hi {name}, choose between rock, papers and scissors")
Cwin = 0
Userwin = 0
Tie = 0
while True:
user_choice = str(input('> '))
user_choice.lower()
if user_choice not in choices:
print("ERROR")
computer_choice = random.choice(choices)
print(f"Computer chooses: {computer_choice}")
if user_choice == "rock":
if computer_choice == "papers":
print("Computer wins!")
Cwin = Cwin + 1
print(int(Cwin) , "Computer victories so far")
elif computer_choice == "scissors":
print(f"{name} wins!")
Userwin = Userwin + 1
print(int(Userwin) , "User victories so far")
if user_choice == "papers":
if computer_choice == "scissors":
print("Computer wins!")
Cwin = Cwin + 1
print(int(Cwin) , "Computer victories so far")
elif computer_choice == "rock":
print(f"{name} wins!")
Userwin = Userwin + 1
print(int(Userwin) , "User victories so far")
if user_choice == "scissors":
if computer_choice == "rock":
print("Computer wins!")
Cwin = Cwin + 1
print(int(Cwin) , "Computer victories so far")
elif computer_choice == "papers":
print(f"{name} wins!")
Userwin = Userwin + 1
print(int(Userwin) , "User victories so far")
if user_choice == computer_choice:
print("Tie!")
Tie = Tie + 1
print(int(Tie) , "Ties so far")
Look here the screenshot of it working properly-

Just add computer choose inside else:
import random
name = str(input("Enter your name:\n"))
choices = ["rock", "papers", "scissors"]
print(f"Hi {name}, choose between rock, papers and scissors")
while True:
user_choice = str(input('> '))
user_choice.lower()
if user_choice not in choices:
print("ERROR")
else:
computer_choice = random.choice(choices)
print(f"Computer chooses: {computer_choice}")
if user_choice == "rock":
if computer_choice == "papers":
print("Computer wins!")
elif computer_choice == "scissors":
print(f"{name} wins!")
if user_choice == "papers":
if computer_choice == "scissors":
print("Computer wins!")
if computer_choice == "rock":
print(f"{name} wins!")
if user_choice == "scissors":
if computer_choice == "rock":
print("Computer wins!")
elif computer_choice == "papers":
print(f"{name} wins!")
if user_choice == computer_choice:
print("Tie!")

Here is a possible implementation:
import random
name = str(input("Enter your name: "))
choices = ["rock", "scissors", "paper"]
print(f"Hi {name}, choose between rock, paper and scissors")
while True:
user_choice = None
while user_choice not in choices:
user_choice = str(input('> '))
user_choice.lower()
computer_choice = random.choice(choices)
print(f"Computer chooses: {computer_choice}")
if user_choice == computer_choice:
print("Tie!")
elif choices[(choices.index(user_choice) + 1) % len(choices)] == computer_choice:
print(f"{name} wins!")
else:
print(f"Computer wins!")
Some insights:
You can accomplish the comparing mechanism with a rounded list, and not explicit comparison.
Do a while loop for the user input until it is correct.

Related

The terminal says that computer_choice doesn’t exist even though it does

WHile I was attempting a simple rock, paper scissors, I ran into this proble. When I execute the file and input the user_input, it says to me that the variable computer_choice doesn’t exist, even though it does exist. I would appreciate if someone could help me, thank you.
import random
user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
while True:
user_input = input("Type Rock/Paper/Scissors or Q to quit. ").lower()
if user_input == "q":
break
if user_input not in options:
continue
random_number = random.randint (0, 2)
computer_choice = options[random_number]
print ("The computer picked:", computer_choice + ".")
if user_input == "rock" and computer_choice == "scissors" :
print("You Won!")
user_wins += 1
continue
elif user_input == "scissors" and computer_choice == "paper" :
print("You Won!")
user_wins += 1
continue
elif user_input == "paper" and computer_pick == "rock" :
print("You Won!")
user_wins += 1
continue
else:
print("You Lost!")
computer_wins += 1
continue
print("You won", user_wins,"times and the computer won", computer_wins, "times.")
print("Goodbye")
You have to be careful with indentation when using python:
import random
user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
while True:
user_input = input("Type Rock/Paper/Scissors or Q to quit. ").lower()
if user_input == "q":
break
if user_input not in options:
continue
# not at this level
# at this level
random_number = random.randint(0, 2)
computer_choice = options[random_number]
print("The computer picked:", computer_choice + ".")
if user_input == "rock" and computer_choice == "scissors":
print("You Won!")
user_wins += 1
continue
elif user_input == "scissors" and computer_choice == "paper":
print("You Won!")
user_wins += 1
continue
elif user_input == "paper" and computer_choice == "rock": #not computer_pick
print("You Won!")
user_wins += 1
continue
Also you wrote computer_pick in line 31, probably you mean computer_choice

How do you have the computer change its choice depending on the input of the player in this game of rock, paper, scissors?

I want the computer to follow a win-stay, lose-switch strategy but I can't seem to get the computer to change its option from rock. Please help!
import random
def game():
game_start
computer_count = 0
user_count = 0
while True:
base_choice = ['scissors', 'paper', 'rock']
computer_choice = 'rock'
user_choice = input('(scissors, paper, rock) Type your choice: ').strip().lower()
print()
computer_wins = 'The computer wins!'
you_win = 'You win!'
print(f'You played {user_choice}, the computer played {computer_choice}')
if user_choice == 'scissors' and computer_choice == 'rock':
computer_choice = 'rock'
elif user_choice == 'paper' and computer_choice == 'scissors':
computer_choice = 'scissors'
elif user_choice == 'rock' and computer_choice == 'paper':
computer_choice = 'paper'
print(computer_wins)
computer_count += 1
if user_choice == 'rock' and computer_choice == 'scissors':
computer_choice = 'paper'
elif user_choice == 'scissors' and computer_choice == 'paper':
computer_choice = 'rock'
elif user_choice == 'paper' and computer_choice == 'rock':
computer_choice = 'scissors'
print(you_win)
user_count += 1
else:
if user_choice == computer_choice:
print('Its a draw!')
computer_count += 0
user_count += 0
print(f'Computer: {computer_count} - You: {user_count}')
print()
game()
It's because you put computer_choice = 'rock' inside the while loop. Having inside causes it to be reset to rock for every play.
Another issue is that your if statements only prints who wins and increases count for the last one.
You can also compress the if statements a little, but that wasn't part of the question, so I didn't do it here.
game_start
computer_count = 0
user_count = 0
def game():
computer_choice = 'rock'
while True:
#base_choice = ['scissors', 'paper', 'rock']
# no point in having an unused list
user_choice = input('(scissors, paper, rock) Type your choice: ').strip().lower()
print()
computer_wins = 'The computer wins!'
you_win = 'You win!'
print(f'You played {user_choice}, the computer played {computer_choice}')
if user_choice == 'scissors' and computer_choice == 'rock':
computer_choice = 'rock'
print(computer_wins)
computer_count += 1
elif user_choice == 'paper' and computer_choice == 'scissors':
computer_choice = 'scissors'
print(computer_wins)
computer_count += 1
elif user_choice == 'rock' and computer_choice == 'paper':
computer_choice = 'paper'
print(computer_wins)
computer_count += 1
if user_choice == 'rock' and computer_choice == 'scissors':
computer_choice = 'paper'
print(you_win)
user_count += 1
elif user_choice == 'scissors' and computer_choice == 'paper':
computer_choice = 'rock'
print(you_win)
user_count += 1
elif user_choice == 'paper' and computer_choice == 'rock':
computer_choice = 'scissors'
print(you_win)
user_count += 1
else:
if user_choice == computer_choice:
print('Its a draw!')
# no point in adding 0
print(f'Computer: {computer_count} - You: {user_count}')
print()
game()
In response to your making it random comment, you need to import the random module.
Here, the base_choice is used, so uncomment it and it'll work:
import random #place at beginning of code
# can instead do `from random import choice`
base_choice = ['scissors', 'paper', 'rock']
# needs to be before you use it in random.choice
# to get random choice, do
computer_choice = random.choice(base_choice)

How to compare a user input to a random output of a list?

I'm trying to compare the input of the user with the answer that the computer prints from the list. Does anyone know why my if statements aren't working?
import random
while True:
def rps():
user = input("Rock Paper Scissors: ")
answers = ["Rock", "Paper", "Scissors"]
print(random.choice(answers))
if user == "r" and answers == "Rock":
print("Tie")
if user == "r" and answers == "Paper":
print("You Lose")
if user == "r" and answers == "Scissors":
print("You Win")
rps()
You need to set a variable to the random choice, like this:
import random
while True:
def rps():
user = input("Rock Paper Scissors: ")
answers = ["Rock", "Paper", "Scissors"]
choice = random.choice(answers)
print(choice)
if user == "r" and choice == "Rock":
print("Tie")
if user == "r" and choice == "Paper":
print("You Lose")
if user == "r" and choice == "Scissors":
print("You Win")
rps()
Be sure to add more logic for other user inputs!
Did you want a program like this?
I configured your code a bit
import random
answers = ["Rock", "Paper", "Scissors"]
options = ['r', 'p', 's', 'q']
def rps():
while True:
print("[r] Rock")
print("[p] Paper")
print("[s] Scissors")
print("[q] Exit")
user = input("Enter your choice: ")
if user not in options:
print("Wrong choice, try again.")
continue
choice = random.choice(answers)
print('Computer answer: ', choice)
if user == 'r':
if choice == "Rock":
print("Tie")
elif choice == "Paper":
print("You lose")
else:
print("You win")
elif user == 'p':
if choice == "Rock":
print("You win")
elif choice == "Paper":
print("Tie")
else:
print("You lose")
elif user == 's':
if choice == "Rock":
print("You lose")
elif choice == "Paper":
print("You win")
else:
print("Tie")
else:
break
rps()

Codecademy Python 2 Rock, Paper, Scissors

I am just starting coding, growing like a baby each day
It gets tough but reviewing my notes and trying to understand/ memorize code.
Please explain for me what to do for this code.
from random import randint
"""This program will enable the user and computer to start a rock paper scissors game"""
options = ["ROCK", "PAPER", "SCISSORS"]
message = {"tie": "Yawn it's a tie!", "won": "Yay you won!", "lost": "Aww you lost!"}
def decide_winner(user_choice, computer_choice):
print("You chose %s") % (user_choice)
print("PC chose %s") % (computer_choice)
if user_choice == computer_choice:
print(message["tie"]) # tie
# user - paper , pc = rock
elif user_choice == options[1] and computer_choice == options[0]:
print(message["won"])
# user - scissor , pc = paper
elif user_choice == options[2] and computer_choice == options[1]:
print(message["won"])
# user - rock , pc - scissors
elif user_choice == options[0] and computer_choice == options[1]:
print(message["won"])
else:
print("YOU LOSE!")
def play_RPS():
user_choice = input("Enter Rock, Paper, Scissors: ")
computer_choice = options[randint(0,2)]
decide_winner(user_choice, computer_choice)
play_RPS()
A couple notes - elif user_choice == options[0] and computer_choice == options[1]: should be elif user_choice == options[0] and computer_choice == options[2]: Your comments were right but you indexed '1' instead of '2' for SCISSORS.
Python is case sensitive, so 'ROCK' will not equal 'Rock'. You need to possibly add the line
user_choice = user_choice.upper() in the function def play_RPS(): before passing it to
decide_winner(user_choice, computer_choice)
Python 2 uses input for things like variables and raw_input for things like strings.
Instead of:
user_choice = input("Enter Rock, Paper, Scissors: ")
Use
user_choice = raw_input("Enter Rock, Paper, Scissors: ")
Inputs are case sensitive
Your options are
options = ["ROCK", "PAPER", "SCISSORS"]
But if a person types "Rock" it shows that they lose
Instead change
user_choice = raw_input("Enter Rock, Paper, Scissors: ")
To
user_choice = raw_input("Enter Rock, Paper, Scissors: ").upper()
from random import randint
"""This program will enable the user and computer to start a rock paper scissors game"""
options = ["ROCK", "PAPER", "SCISSORS"]
message = {"tie": "Yawn it's a tie!", "won": "Yay you won!", "lost": "Aww you lost!"}
best_of_three = 3
def decide_winner(user_choice, computer_choice):
print('You chose %s' % user_choice)
print("PC chose %s" % computer_choice)
if user_choice == computer_choice:
print(message["tie"]) # tie
# user - paper , pc = rock
elif user_choice == options[1] and computer_choice == options[0]:
print(message["won"])
# user - scissor , pc = paper
elif user_choice == options[2] and computer_choice == options[1]:
print(message["won"])
# user - rock , pc - scissors
elif user_choice == options[0] and computer_choice == options[1]:
print(message["won"])
else:
print("YOU LOSE!")
def play_RPS():
user_choice = input("Enter Rock, Paper, Scissors: ").upper()
computer_choice = options[randint(0, 2)]
decide_winner(user_choice, computer_choice)
play_RPS()

When running this code, why does the loop not wait for my response?

import random
def rock_paper_scissors(choice):
computer_choice = random.choice(['rock', 'paper', 'scissors'])
while True:
if choice == computer_choice:
print("Tie! Play again.")
choice
elif choice.lower() == 'quit':
break
elif choice.lower() == 'rock' and computer_choice.lower() == 'paper':
print("TRY AGAIN!", computer_choice.lower(), "beats", choice.lower())
choice
elif choice.lower() == 'rock' and computer_choice.lower() == 'scissors':
print("YOU WON!", choice.lower(), "beats", computer_choice.lower())
choice
elif choice.lower() == 'paper' and computer_choice.lower() == 'scissors':
print("TRY AGAIN!", computer_choice.lower(), "beats", choice.lower())
choice
elif choice.lower() == 'paper' and computer_choice.lower() == 'rock':
print("YOU WON!", choice.lower(), "beats", computer_choice.lower())
choice
elif choice.lower() == 'scissors' and computer_choice.lower() == "rock":
print("TRY AGAIN!", computer_choice.lower(), "beats", choice.lower())
choice
elif choice.lower() == 'scissors' and computer_choice.lower() == "paper":
print("YOU WON!", choice.lower(), 'beats', computer_choice.lower())
choice
else:
print("Sorry, invalid.")
choice
print(rock_paper_scissors(input("Rock paper or scissors (enter 'q' to quit): ")))
When this code is run, whatever is in the print in the elif is repeated over and over and over again in the run box. I don't know if I should fix the while statement or add additional code in the elif statements. The input works fine, but I don't know what to add to the while loop. (I am a beginner Python programmer)
The input statement is not in the scope of the while loop, so it is only called once.
Once in the while loop, there is nothing changing the choice variable and hence the same print statement get triggered over and over.
Moving the input statement into the while loop along with the the computer choice initialisation (so the computer can choose a new option each go) solves your problem.
import random
def rock_paper_scissors():
while True:
computer_choice = random.choice(['rock', 'paper', 'scissors'])
choice = input("Rock paper or scissors (enter 'q' to quit): ")
if choice == computer_choice:
print("Tie! Play again.")
elif choice.lower() == 'quit':
break
elif choice.lower() == 'rock' and computer_choice.lower() == 'paper':
print("TRY AGAIN!", computer_choice.lower(), "beats", choice.lower())
elif choice.lower() == 'rock' and computer_choice.lower() == 'scissors':
print("YOU WON!", choice.lower(), "beats", computer_choice.lower())
elif choice.lower() == 'paper' and computer_choice.lower() == 'scissors':
print("TRY AGAIN!", computer_choice.lower(), "beats", choice.lower())
elif choice.lower() == 'paper' and computer_choice.lower() == 'rock':
print("YOU WON!", choice.lower(), "beats", computer_choice.lower())
elif choice.lower() == 'scissors' and computer_choice.lower() == "rock":
print("TRY AGAIN!", computer_choice.lower(), "beats", choice.lower())
elif choice.lower() == 'scissors' and computer_choice.lower() == "paper":
print("YOU WON!", choice.lower(), 'beats', computer_choice.lower())
else:
print("Sorry, invalid.")
rock_paper_scissors()
I thought I'd share an alternative way of writing this that may be of help to a beginner. The goals are:
To reduce repetition, so you only have one print("You Lose") rather than three.
To separate the winning logic into a separate function, which makes it easier to test the logic part and allows code reuse.
import random
def did_player_win(computer, player):
# Returns None for a tie, True for a win, False for a lose
if computer == player:
return None
if computer == 'paper':
return False if player == 'rock' else True
if computer == 'scissors':
return False if player == 'paper' else True
if computer == 'rock':
return False if player == 'scissors' else True
def play():
while True:
player = input("Rock, paper or scissors (enter 'q' to quit): ")
player = player.lower()
if player not in ['rock', 'paper', 'scissors']:
break
computer = random.choice(['rock', 'paper', 'scissors'])
player_won = did_player_win(computer, player)
if player_won is True:
print("YOU WON! {0} beats {1}".format(player, computer))
elif player_won is False:
print("TRY AGAIN! {0} beats {1}".format(computer, player))
else:
print("Tie! Both chose {0}".format(player))
play()

Categories