如何修复 if 语句以使用字符串?

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

我必须制作剪刀石头布游戏,但是当我尝试使用 str(.....)

将输入转换为字符串时,if 语句不起作用

我在这里使用整数来确保代码在其他情况下可以正常工作,但它不适用于字符串。

当我 运行 这段代码时,我也无法将输入加下划线,如何做到这一点?

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.")

我每次 运行 代码时都会收到此错误:

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

我做错了什么?

对于您的每个案例,您都在根据字符串检查变量的值。它们每个的字符串可以是 "R"、"S" 或 "P",并且在您的 if 语句中,您应该这样写它们

例如

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

等等。

正如@jedwards 所说,您正在使用 python3,而 input() returns 是一个字符串,因此不需要第一行和第二行中的 str() 包装器

你可以简单地说

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