Nischal Jogani
Nischal Jogani

Reputation: 1

How can we write a simple code that generates a random but excluding the user's input in python

I am making a rock paper scissors game and for that I want the computer to choose a random choice excluding the player's choice so if a player chooses rock then it should choose randomly between paper and scissors. Can anyone help me out?

This is my code:

symbols = [rock,paper,scissors]
player_input = input("Please type 1 for rock, 2 for paper, and 3 for scissors. ")
player_choice = int(player_input) - 1

Upvotes: 0

Views: 300

Answers (3)

user15773347
user15773347

Reputation:

You could do something like that:

from random import choice

symbols = ["rock","paper","scissors"]

try:    
    player_input = int(input("Please type 1 for rock, 2 for paper, and 3 for scissors. ")) - 1
except (ValueError, TypeError):
    print("Not a valid input")
else:
    symbols_two = [thing for thing in symbols if thing != symbols[player_input]]

    print('random answer: {}'.format(choice(symbols_two)))
  • this code is not tested for errors

Upvotes: 0

jrsenthilk
jrsenthilk

Reputation: 9

You can try something along this line (assuming I am continuing from your code above):

import random
remaining_symbol = symbols
remaining_symbol.pop(player_choice)
result = remaining_symbol[random.randint(0, len(remaining_symbol))]
print(result) #this should give you the answer

I have not tested this code but it should be along this idea.

Upvotes: 0

John Mommers
John Mommers

Reputation: 140

You could try this code. The first choice will be removed from the list of choices.

c = [1,2,3] # 3 choices
a = random.choice(c) # pick the first (e.g. by input player)
print (a) 
c.remove(a) # remove it from the list of choices
b = random.choice(c) # pick the second (e.g. by computer)
print (b) 

Upvotes: 1

Related Questions