pythonpython-3.xif-statementundefined-variable

How do I fix the if statements to work with strings?


I have to make a rock paper scissors game but it the if statements wont work when I try to convert the input into string with str(.....)

I used integers here to make sure the code works fine otherwise but it just wont work with strings.

I'm also having trouble with making the input underlined when I run this code, how does one do that?

player_1 = str(input("Enter Player 1 choice (R, P, or S): "))
player_2 = str(input("Enter Player 2 choice (R, P, or S): "))


if player_1 == S and player_2 == S:
    print("A tie!")

elif player_1 == R and player_2 == R:
    print("A tie!")

elif player_1 == P and player_2 == P:
    print("A tie!")

elif player_1 == R and player_2 == 2:
    print("Rock beats scissors! Player 1 wins.")

elif player_1 == S and player_2 == R:
    print("Rock beats scissors! Player 2 wins.")

elif player_1 == 9 and player_2 == R:
    print("Paper beats rock! Player 1 wins.")

elif player_1 == R and player_2 == P:
    print("Paper beats rock! Player 2 wins.")

elif player_1 == S and player_2 == P:
    print("Scissors beat paper! player 1 wins.")

elif player_1 == P and player_2 == S:
    print("Scissors beat paper! player 2 wins.")

I get this error every time I run the code:

Enter Player 1 choice (R, P, or S): S
Enter Player 2 choice (R, P, or S): S
Traceback (most recent call last):
  File "D:\CP 104\**********\src\t03.py", line 16, in <module>
    if player_1 == S and player_2 == S:
NameError: name 'S' is not defined

What am I doing wrong?


Solution

  • For each of your cases, you are checking the value of a variable against a string. The string for each of them can be "R", "S", or "P", and in your if statements, you should write them as such

    for example

    if player_1 == "S" and player_2 == "S":
    

    and so on.

    and as @jedwards said, you are using python3, and the input() returns a string, so the str() wrapper in your first and second lines are not needed

    you can simply say

    player_1 = input("Enter Player 1 choice (R, P, or S): ")
    player_2 = input("Enter Player 1 choice (R, P, or S): ")