石头剪刀-Python 3-初学者

石头剪刀-Python 3-初学者,python,if-statement,python-3.x,Python,If Statement,Python 3.x,我想模拟一个石头剪刀布游戏,这就是我到目前为止所做的。它不允许我在scoregame函数中输入字母。我怎样才能解决这个问题 def scoregame(player1, player2): if player1 == R and player2 == R: scoregame = "It's a tie, nobody wins." if player1 == S and player2 == S: scoregame == "It's a tie

我想模拟一个石头剪刀布游戏,这就是我到目前为止所做的。它不允许我在
scoregame
函数中输入字母。我怎样才能解决这个问题

def scoregame(player1, player2):
    if player1 == R and player2 == R:
        scoregame = "It's a tie, nobody wins."
    if player1 == S and player2 == S:
        scoregame == "It's a tie, nobody wins."
    if player1 == P and player2 == P:
        scoregame = "It's a tie, nobody wins."
    if player1 == R and player2 == S:
        scoregame = "Player 1 wins."
    if player1 == S and player2 == P:
        scoregame = "Player 1 wins."
    if player1 == P and player2 == R:
        scoregame = "Player 1 wins."
    if player1 == R and player2 == P:
        scoregame == "Player 2 wins."
    if player1 == S and player2 == R:
        scoregame == "Player 2 wins."
    if player1 == P and player2 == S:
        scoregame = "Player 2 wins."

print(scoregame)
您需要针对字符串进行测试;您现在正在针对变量名进行测试:

if player1 == 'R' and player2 == 'R':
但您可以通过测试两个玩家是否相等来简化两个玩家选择相同选项的情况:

if player1 == player2:
    scoregame = "It's a tie, nobody wins."
接下来,我将使用一个映射,一个字典,来编码什么优于什么:

beats = {'R': 'S', 'S': 'P', 'P': 'R'}

if beats[player1] == player2:
    scoregame = "Player 1 wins."
else:
    scoregame = "Player 2 wins."
现在您的游戏只需进行两次测试。所有这些加在一起:

def scoregame(player1, player2):
    beats = {'R': 'S', 'S': 'P', 'P': 'R'}
    if player1 == player2:
        scoregame = "It's a tie, nobody wins."
    elif beats[player1] == player2:
        scoregame = "Player 1 wins."
    else:
        scoregame = "Player 2 wins."
    print(scoregame)

您使用的是不带引号的字母,因此它要查找一个名为p的变量,但您需要的是字符串“p”,因此请将字母加引号:

if player1 == "P" and player2 == "S":

您能否显示接受输入并显示
scoregame
的代码?因为从描述和最后一行来看,我怀疑你也弄错了。另外,请描述问题。“不让我输入字母”是什么意思。它是否会在您运行程序时立即引发异常?当它调用
scoregame
函数时?在
scoregame
功能中?如果是这样,请提供异常和回溯。或者它运行成功,但做了错误的事情?如果是这样,请描述您的输入、预期输出和实际输出。另外,作为补充说明,在这种情况下,函数和变量使用相同的名称实际上并不是错误的,但这很容易混淆,最好避免使用。@Duality:有一天您将编写一个返回函数的递归函数,并愉快地调试它。:)请不要诋毁你的问题。我已经把那个编辑回滚了。@BradLarson:OP。如果他使用
elif
而不是
If
,他可以将整个内容缩减为5个子句。但你是对的,字典让他把它减少到3,而且更难出错。@jerry2144:为什么会有污损?如果你在作业中使用了我的帖子,那是你的问题,不是我的问题。请不要破坏我的作品,因为它让你感到尴尬。有趣的是,如果他的老师在谷歌上搜索了你版本代码的第一行,这个问题无论如何都会是第一个搜索结果。因此,现在的证据不是学生提出与你完全相同的代码(这证明不了什么,因为这是显而易见的编写方式…),而是学生故意复制和粘贴代码,然后试图掩盖代码。(这就是为什么我不理解讨厌这样的老师…)