import random
def rpc():
a = ["rock", "paper", "scissor"]
b = random.choice(a)
print(b)
userinput = input('please type rock, paper or scissor:')
if userinput == "":
print("please print the right thing")
rpc()
if userinput != "rock":
print("type the right thing!")
rpc()
if userinput != "paper":
print("type the right thing!")
rpc()
if userinput != "scissor":
print("type the right thing!")
rpc()
while b == userinput:
print("it is a draw, do you want to play another one?")
c = input("type 'y' if you want to play one more time or press 'n': ")
if c == 'y':
rpc()
elif c =='n':
break
else:
print("print the right words please")
if b == 'rock' and userinput == 'paper':
print("you win!")
rpc()
elif b == 'rock' and userinput == 'scissor':
print("you lost")
rpc()
elif b == 'paper' and userinput == 'scissor':
print("you win!")
rpc()
elif b == 'paper' and userinput == 'rock':
print("you lost!")
rpc()
elif b == 'scissor' and userinput == 'rock':
print("you win!")
rpc()
elif b == 'scissor' and userinput == 'paper':
print("you lost!")
rpc()
rpc()
This is my code for rock paper and scissor, it's pretty simple but when I run my code and input my rock, paper and scissor, I get my please print the right thing statement, O have no idea why it's happening, any help would be wonderful, thank you!
Lets clean this up....
userinput = input('please type rock, paper or scissor:')
while userinput not in acceptable_inputs:
userinput = input('please type rock, paper or scissor:')
opponents_choice = random.choice(objects)
# Check and print. Loop to keep playing - 2 out of 3 wins....
import random
def winner(riya,siya):
if (riya==siya):
return None
elif (riya=="s"):
if (siya=="p"):
return False
elif(siya=="k"):
return True
elif (riya=="p"):
if (siya=="s"):
return False
elif (siya=="k"):
return True
elif (riya=="k"):
if (siya=="s"):
return True
elif (siya=="p"):
return False
print("riya pick: stone(s) paper(p) sessior(k)")
a= random.randint(1,3)
if a==1:
riya="s"
elif a==2:
riya="p"
elif a==3:
riya="k"
siya=input(" siya pick: stone(s) paper(p) sessior(k)")
b=winner(riya,siya)
print(f"riya pick{riya}")
print(f"siya pick {siya}")
if b==None:
print("tie")
elif b:
print("winner")`enter code here`
else:enter code here
print("loose")
Related
I have made a rock, paper, scissors game in python. How would I get the game to repeat over if the user enters yes? My code appears to go into a never ending loop when the user enters anything but rock, paper, or scissors
Also I'm trying to learn when and where I should use functions. If you could show a pythonic way to separate the finished code into functions I would greatly appreciate that.
import random
a = ["rock", "paper", "scissors"]
word = input('Enter rock, paper, or scissors: ')
def game():
while True:
try:
if word not in a:
raise ValueError #this will send it to the print message and back to the input option
break
except ValueError:
print(" You must enter rock, paper, or scissors.")
comp_draw = random.choice(a)
print('The computer drew ' + comp_draw)
if comp_draw == 'rock' and word=='rock':
print('It was a tie')
elif comp_draw == 'paper' and word=='paper':
print('It was a tie')
elif comp_draw == 'scissors' and word=='scissors':
print('It was a tie')
elif comp_draw == 'paper' and word=='rock':
print('you lost')
elif comp_draw == 'rock' and word=='paper':
print('you won!')
elif comp_draw == 'rock' and word=='scissors':
print('you lost')
elif comp_draw == 'scissors' and word=='rock':
print('you won!')
elif comp_draw == 'scissors' and word=='rock':
print('you won!')
elif comp_draw == 'scissors' and word=='rock':
print('you won!')
game()
play_again = input('would you like to play again: ')
Wasn't missing much, all you needed was a loop
import random
a = ["rock", "paper", "scissors"]
word = input('Enter rock, paper, or scissors: ')
def game():
while True:
try:
if word not in a:
raise ValueError #this will send it to the print message and back to the input option
break
except ValueError:
print(" You must enter rock, paper, or scissors.")
comp_draw = random.choice(a)
print('The computer drew ' + comp_draw)
if comp_draw == 'rock' and word=='rock':
print('It was a tie')
elif comp_draw == 'paper' and word=='paper':
print('It was a tie')
elif comp_draw == 'scissors' and word=='scissors':
print('It was a tie')
elif comp_draw == 'paper' and word=='rock':
print('you lost')
elif comp_draw == 'rock' and word=='paper':
print('you won!')
elif comp_draw == 'rock' and word=='scissors':
print('you lost')
elif comp_draw == 'scissors' and word=='rock':
print('you won!')
elif comp_draw == 'scissors' and word=='rock':
print('you won!')
elif comp_draw == 'scissors' and word=='rock':
print('you won!')
play_again = "yes"
while play_again == "yes":
game()
play_again = input('would you like to play again: ').lower()
Instead of :
game()
play_again = input("...")
Put your game in a loop as follow :
while True:
play_again = input ("would you like to play")
if play_again == "yes" :
game()
continue
elif play_again == "no" :
break
else:
print("answer by yes or no")
continue
There was also an issue of the variable word being outside the scope of game(). It would work on the first run but not the consequent runs thereafter. This code seems to work fine and as expected.
import random
a = ["rock", "paper", "scissors"]
def game():
while True:
try:
word = input('Enter rock, paper, or scissors: ')
if word not in a:
raise ValueError # this will send it to the print message and back to the input option
break
except ValueError:
print(" You must enter rock, paper, or scissors.")
comp_draw = random.choice(a)
print('The computer drew ' + comp_draw)
if comp_draw == 'rock' and word =='rock':
print('It was a tie')
elif comp_draw == 'paper' and word =='paper':
print('It was a tie')
elif comp_draw == 'scissors' and word =='scissors':
print('It was a tie')
elif comp_draw == 'paper' and word =='rock':
print('you lost')
elif comp_draw == 'rock' and word =='paper':
print('you won!')
elif comp_draw == 'rock' and word =='scissors':
print('you lost')
elif comp_draw == 'scissors' and word =='rock':
print('you won!')
elif comp_draw == 'scissors' and word =='rock':
print('you won!')
elif comp_draw == 'scissors' and word =='rock':
print('you won!')
if __name__ == "__main__":
game()
while True:
if input('Would you like to play_again? ') == 'yes':
game()
else:
break
I am looking for ways to shorten and simplify my python code. Here is one example of one small rock/paper/scissors game I wrote earlier. The code kinda looks too long to me and I want to try to learn how to shorten my code.
import random
user_wins = 0
comp_wins = 0
game_limit = 0
options = ["rock","paper","scissors"]
print("Welcome to Rock Paper Scissors, This is a Best of 5")
while True:
user_input = input("Type in Rock/Paper/Scissors or Q to quit: ").lower()
if user_input == "q":
break
elif user_input not in options:
print("type in a valid word next time")
continue
game_limit += 1
if game_limit == 5 and comp_wins > user_wins:
print("The game is over, YOU LOST!")
elif game_limit == 5 and comp_wins < user_wins:
print("The game is over, YOU WON!")
random_number = random.randint(0,2)
comp_input = options[random_number]
print("Computer picked", comp_input)
if user_input == "rock" and comp_input == "scissors":
print("You win")
user_wins += 1
elif user_input == "rock" and comp_input == "rock":
print("its a draw")
elif user_input == "rock" and comp_input == "paper":
print("You lose!")
comp_wins += 1
if user_input == "scissors" and comp_input == "paper":
print("You win")
user_wins += 1
elif user_input == "scissors" and comp_input == "scissors":
print("its a draw")
elif user_input == "scissors" and comp_input == "rock":
print("You lose!")
comp_wins += 1
if user_input == "paper" and comp_input == "rock":
print("You win")
user_wins += 1
elif user_input == "paper" and comp_input == "paper":
print("its a draw")
elif user_input == "paper" and comp_input == "scissors":
print("You lose!")
comp_wins += 1
Yes. You could simplify your logic by having compound and/or tests for the player and user. Following is a revised version of your code with some simplified logic.
import random
user_wins = 0
comp_wins = 0
game_limit = 0
options = ["rock","paper","scissors"]
print("Welcome to Rock Paper Scissors, This is a Best of 5")
while True:
if game_limit >= 5: # Tweak
if comp_wins > user_wins:
print("The game is over, YOU LOST!")
break
if comp_wins < user_wins:
print("The game is over, YOU WON!")
break
else:
print("We go to sudden death!")
user_input = input("Type in Rock/Paper/Scissors or Q to quit: ").lower()
if user_input == "q":
break
elif user_input not in options:
print("type in a valid word next time")
continue
game_limit += 1
random_number = random.randint(0,2)
comp_input = options[random_number]
print("Computer picked", comp_input)
if user_input == "rock" and comp_input == "scissors" or user_input == "paper" and comp_input == "rock" or user_input == "scissors" and comp_input == "paper":
print("You win")
user_wins += 1
elif user_input == "rock" and comp_input == "paper" or user_input == "paper" and comp_input == "scissors" or user_input == "scissors" and comp_input == "rock":
print("You lose!")
comp_wins += 1
else:
print("It's a draw")
This way all of the scenarios where the user can win are in one logical test and all of the scenarios where the computer can win are in another logical test. If neither test is true, then the default would have to be a draw.
Also, I tweaked game limit test because if the computer and user have the same score when the game limit is reached, the test result would be false and the game would then continue on and not stop. So there is a bit of additional code to handle a tie after five rounds.
Give that a try.
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
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
So i wrote my first Rock, Paper, Scissors in Python and it nearly works. The problem is that it sometimes reads "scissors" as an invalid input, which seems to me completely randomly and i dont know what the problem is. Hoping for an easy fix for it. Here's the code:
import time
import random
choice_list = ["Rock", "Paper", "Scissors"]
def game():
won = False
lost = False
while not won and not lost:
user = input("Enter your choice from Rock, Paper or Scissors: ")
user_i = user.lower()
com_1 = random.choice(choice_list)
com_choice = com_1.lower()
if com_choice == user_i:
print("Draw, try again!")
elif com_choice == "rock" and user_i == "paper":
won = True
elif com_choice == "rock" and user_i == "scissors":
lost = True
elif com_choice == "paper" and user_i == "rock":
lost = True
elif com_choice == "paper" and user_i == "scissors":
won = True
elif com_choice == "scissors" and user_i == "rock":
won = True
elif com_choice == "scissors" and user_i == "paper":
lost = True
elif user != "scissors" or "paper" or "rock":
print("Invalid choice, try again...")
if won:
print("Congrats you won, the PC chose " + com_1 + "!")
won = False
if lost:
print("You lost, the PC chose " + com_1 + "!")
lost = False
play_again = "yes"
while play_again.lower() == "yes":
game()
play_again = input("Would u like to play again? ")
if play_again.lower() != "yes":
print("Goodbye!")
time.sleep(3)
The fix:
elif user_i not in ("scissors" or "paper" or "rock"):
print("Invalid choice, try again...")
You were using user instead of user_i. So, when user is Scissors, the elif condition will fail("Scissors" != "scissors") and return Invalid choice.
Also,
elif user != "scissors" or "paper" or "rock" is evaluated as
elif (user != 'scissors') or 'paper' or 'rock' which is not exactly what you intend although it doesn't affect your results. Instead, you should write
elif user_i not in ("scissors", "paper", "rock"):
Actually, you don't even need the last elif since you have already checked for all the valid inputs in the previous if-else statements.
In your program, when validating input for invalid words, you are using raw input user. This could have different case from user_i = user.lower().
Try with the below line:
elif ((user_i != "scissors") and (user_i != "paper") and (user_i != "rock")):
print("Invalid choice, try again...")
If still you get issues, pls let us know your input.
I'm very new to Python and decided to set myself a challenge of programming a Rock, Paper, Scissors game without copying someone else's code. However, I need help from a Pythonista grown-up!
I've seen many other variations on Rock, Paper, Scissors, on here but nothing to explain why my version isn't working. My program basically follows this format: set empty variables at start, define 4 functions that prints intro text, receives player input, randomly picks the computer's choice, then assesses whether its a win or a loss for the player.
This is all then stuck in a while loop that breaks once the player selects that they don't want to play anymore. (This bit is working fine)
However, whenever I run the code, it just always gives a draw and doesn't seem to store any data for the computer's choice function call. Does anybody know what I'm doing wrong?
Many thanks!
import random
playerAnswer = ''
computerAnswer = ''
winsTotal = 0
timesPlayed = 0
def showIntroText():
print('Time to play Rock, Paper, Scissors.')
print('Type in your choice below:')
def playerChoose():
playerInput = input()
return
def computerChoose():
randomNumber = random.randint(1, 3)
if randomNumber == 1:
computerPick = 'Paper'
elif randomNumber == 2:
computerPick = 'Scissors'
else:
computerPick = 'Rock'
return
def assessResult():
if playerAnswer == computerAnswer:
print('Draw!')
elif playerAnswer == 'Rock' and computerAnswer == 'Paper':
print('Paper beats Rock. You lose!')
elif playerAnswer == 'Paper' and computerAnswer == 'Scissors':
print('Scissors cuts Paper. You lose!')
elif playerAnswer == 'Scissors' and computerAnswer == 'Rock':
print('Rock blunts Scissors. You lose!')
else:
print('You win!')
winsTotal += 1
return
while True:
timesPlayed += 1
showIntroText()
playerAnswer = playerChoose()
computerAnswer = computerChoose()
assessResult()
print('Do you want to play again? (y/n)')
playAgain = input()
if playAgain == 'n':
break
print('Thank you for playing! You played ' + str(timesPlayed) + ' games.')
You have missed returning values in most of the case.
** Add 'return playerInput ' in playerChoose() instead of only return.
** Add ' return computerPick ' in computerChoose() instead of return.
** Initialize winsTotal variable before using it as 'winsTotal = 0' in assessResult().
** Variables you have intialized at the start of program are out of scope for functions.
Please check this StackOverFlow link for understanding scope of variables in python.
** Add 'return winsTotal' in assessResult() instead of return.
import random
def showIntroText():
print('Time to play Rock, Paper, Scissors.')
print('Type in your choice below:')
def playerChoose():
playerInput = input()
return playerInput
def computerChoose():
randomNumber = random.randint(1, 3)
if randomNumber == 1:
computerPick = 'Paper'
elif randomNumber == 2:
computerPick = 'Scissors'
else:
computerPick = 'Rock'
return computerPick
def assessResult(winsTotal):
if playerAnswer == computerAnswer:
print('Draw!')
elif playerAnswer == 'Rock' and computerAnswer == 'Paper':
print('Paper beats Rock. You lose!')
elif playerAnswer == 'Paper' and computerAnswer == 'Scissors':
print('Scissors cuts Paper. You lose!')
elif playerAnswer == 'Scissors' and computerAnswer == 'Rock':
print('Rock blunts Scissors. You lose!')
else:
print('You win!')
winsTotal += 1
return winsTotal
total_win = 0
while True:
timesPlayed += 1
showIntroText()
playerAnswer = playerChoose()
computerAnswer = computerChoose()
total_win = assessResult(total_win)
print('Do you want to play again? (y/n)')
playAgain = input()
if playAgain == 'n':
break
print('Thank you for playing! You played ' + str(timesPlayed) + ' games.' + 'Out of which you won '+ str(total_win))
Output:
C:\Users\dinesh_pundkar\Desktop>python c.py
Time to play Rock, Paper, Scissors.
Type in your choice below:
"Rock"
You win!
Do you want to play again? (y/n)
"y"
Time to play Rock, Paper, Scissors.
Type in your choice below:
"Rock"
Draw!
Do you want to play again? (y/n)
"y"
Time to play Rock, Paper, Scissors.
Type in your choice below:
"Rock"
Paper beats Rock. You lose!
Do you want to play again? (y/n)
"y"
Time to play Rock, Paper, Scissors.
Type in your choice below:
"Rock"
Paper beats Rock. You lose!
Do you want to play again? (y/n)
"n"
Thank you for playing! You played 4 games.Out of which you won 1
add input and return in your functions
def computerChoose And def assessResultreturn None
for Example by this code you can play this game :
import random
playerAnswer = ''
computerAnswer = ''
winsTotal = 0
timesPlayed = 0
def playerChoose():
playerInput = input("insert:")
return playerInput
def computerChoose():
randomNumber = random.randint(1, 3)
if randomNumber == 1:
computerPick = 'Paper'
elif randomNumber == 2:
computerPick = 'Scissors'
else:
computerPick = 'Rock'
return computerPick
def assessResult(playerAnswer, computerAnswer):
if playerAnswer == computerAnswer:
print('Draw!')
elif playerAnswer == 'Rock' and computerAnswer == 'Paper':
print('Paper beats Rock. You lose!')
elif playerAnswer == 'Paper' and computerAnswer == 'Scissors':
print('Scissors cuts Paper. You lose!')
elif playerAnswer == 'Scissors' and computerAnswer == 'Rock':
print('Rock blunts Scissors. You lose!')
else:
print('You win!')
return
while True:
timesPlayed += 1
playerAnswer = playerChoose()
computerAnswer = computerChoose()
assessResult(playerAnswer,computerAnswer)
print('Do you want to play again? (y/n)')
playAgain = input()
if playAgain == 'n':
break
print('Thank you for playing! You played ' + str(timesPlayed) + ' games.')
It is always a draw because you aren't returning the answers from your function, both playerAnswer and computerAnswer return None
As some of people said playerChoose() and computerChoose() return with None
Modifidy these statement playerChoose() -> return playerInput
and computerChoose() -> return computerPick
AS well as you have to use global variable. Insert this row
global winsTotal
in the assessResult().