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

时间:2018-10-04 21:22:02

标签: python python-3.x if-statement undefined-variable

我必须做一个剪刀石头布游戏,但是当我尝试使用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

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

对于每种情况,您都在根据字符串检查变量的值。每个字符串都可以是“ R”,“ S”或“ P”,并且在if语句中,您应该这样写

例如

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

以此类推。

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

您可以简单地说

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