Data Structure and Algorithms using Python

Question:

The strings may have any casing. Rock, ROCK, roCK are all possible and valid.
Anyone can help on how to allow my code to accept any case like rOcK and all… ?

player1 = input('Enter rock/paper/scissors: ')
player2 = input('Enter rock/paper/scissors: ')

if (player1 == player2):
    print("The game is a Tie")
elif (player1 == 'rock' and player2 == 'scissors'):
    print("player 1 wins")
elif (player1 == 'rock' and player2 == 'paper'):
    print("player 2 wins")
elif (player1 == 'paper' and player2 == 'rock'):
    print("player 1 wins")
elif (player1 == 'paper' and player2 == 'scissors'):
    print("player 2 wins")
elif (player1 == 'scissors' and player2 == 'paper'):
    print("player 1 wins")
elif (player1 == 'scissors' and player2 == 'rock'):
    print("player 2 wins")
else:
    print("Invalid input")

My code is perfectly running just can’t figure out how to code to allow it accept any case.

Asked By: DarkKnight

||

Answers:

You can use string.lower() or string.upper() in Python, which converts the string to lower/upper case letters. This way you can have your string all upper or all lower, whichever you want.

f.e: if player1='ROCK' and you compare by player1.lower(), your player1 will be evaluated as rock instead of ROCK

string.lower() documentation:

The lower() method converts all uppercase characters in a string into lowercase characters and returns it.

Answered By: Alexsen

You can accept the inputs in any case and convert both inputs to same case before writing the conditions like this:

player1 = input('Enter rock/paper/scissors: ') 
player2 = input('Enter rock/paper/scissors: ')
player1 = player1.lower()
player2 = player2.lower()

# then continue with if cases
Answered By: Suyash Krishna
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.