我必须制作一个石头剪刀布游戏,但是当我尝试将输入转换为字符串时,if 语句不起作用str(.....)
我在这里使用了整数来确保代码在其他情况下正常工作,但它不适用于字符串。
我在运行此代码时也遇到使输入下划线的问题,如何做到这一点?
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**********srct03.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(( 返回一个字符串,因此不需要第一行和第二行中的 str(( 包装器
你可以简单地说
player_1 = input("Enter Player 1 choice (R, P, or S): ")
player_2 = input("Enter Player 1 choice (R, P, or S): ")