Python Basic Coding Games

Table of contents

Rock, Paper and Scissors

  1. You’re going to need to import the module you’ll use to simulate the computer’s choices: import random

2)Taking input from a user is pretty straightforward in Python. The goal here is to ask the user what they would like to choose as an action and then assign that choice to a variable: user_input = input("Type Rock/Paper/Scissors or Q to quit: ").lower()

This will prompt the user to enter a selection and save it to a variable for later use. Now that the user has selected an action, the computer needs to decide what to do.

3)Random selections are a great way to have the computer choose a pseudorandom value.

You can use random.choice() to have the computer randomly select between the actions: random_number = random.randint(0, 2) # rock: 0, paper: 1, scissors: 2 computer_pick = options[random_number]

  1. Determine a Winner

Now that both players have made their choice, you just need a way to decide who wins. Using an ifelifelse block, you can compare players’ choices and determine a winner:

if user_input == "rock" and computer_pick == "scissors": print("You won!") user_wins += 1

elif user_input == "paper" and computer_pick == "rock": print("You won!") user_wins += 1

elif user_input == "scissors" and computer_pick == "paper": print("You won!") user_wins += 1

else: print("You lost!") computer_wins += 1

By comparing the tie condition first, you get rid of quite a few cases. If you didn’t do that, then you’d need to check each possible action user_action and compare it against each possible action for computer_action. By checking the tie condition first, you’re able to know what the computer chose with only two conditional checks of computer_action.

5) Complete Code

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) # rock: 0, paper: 1, scissors: 2 computer_pick = options[random_number] print("Computer picked", computer_pick + ".")

if user_input == "rock" and computer_pick == "scissors": print("You won!") user_wins += 1

elif user_input == "paper" and computer_pick == "rock": print("You won!") user_wins += 1

elif user_input == "scissors" and computer_pick == "paper": print("You won!") user_wins += 1

else: print("You lost!") computer_wins += 1

print("You won", user_wins, "times.") print("The computer won", computer_wins, "times.") print("Bye")