In this article, we have built a program that plays rock paper scissors in Python. First, we show you how the program works by using some example inputs, next we move on to the code itself, and then wrap up this article by explaining the code
The code gets an input from the user, here entered as Rock(R), and then we get a random response from the computer’s side as Scissors(S), which in this case is considered a win.
Your Turn: R Computer: S You Win!!!
This time again, we enter Rock(R), but then we get the response back as Rock(R) again. Therefore we get the output as a tie
Your Turn: R Computer: R ==TIE==
import random user = input("Your Turn: ").upper() comp = random.choice(['R','P','S']) print("Computer:",comp) win = (user=='R'and comp=='S') or (user=='S' and comp=='P')or(user=='P'and comp=='R') if win: print("You Win!") elif user == comp : print('==TIE==') else: print('You Lose!')
Line 1: We import random so that we can make random choices for the computer
Line 3: Now get the input from the user and then store it in a variable named user.
We use .upper() so that there will be no case conflict
Line 4: Here we store the computer’s move in another variable named comp, but here, we use random.choice(["R","P","S"])
Therfore, one of the choices is randomly selected and stored
Line 6: And now, we print out the computer’s random choice
Line 8: This line of code is pretty important.
Here we store the conditions for a win in a variable named win
Line 10-15: If the conditions of win are satisfied, we get the output as “You win!”, if both the moves were the same, we get “==TIE==”
TO SUM UP…
Today we have seen how to build the Rock Paper Scissors in python using the Random Li. If you have any questions or feedback on this, feel free to post in the comments section below.
If you are on your way to becoming a Python expert, you might find our site really helpful. Hit this link for more python related posts
Check it out, it’s Simply the Best Code.