用fi输入Python石头,布,剪刀

2024-04-25 22:38:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着拿一个文件,第一行有一个数字,它决定了有多少手石头布剪刀在玩。看起来像这样。你知道吗

3
Rock Paper
Paper Rock
Scissors Scissors

我应该写些东西来证明谁赢了。这是我到目前为止得出的结论。(我刚从学校休学2年,对python非常陌生,因此我对任何无知表示歉意。)

谢谢

def RockPaperScissors (filename):


    f_in = open(filename , 'r')
    nTimes = int(f_in.readline())
    playerA = ' '
    playerB = ''
    for x in range(nTimes):
        choices = f_in.readline().split()
        playerA = choices[0:1]
        playerB= choices[-1:]

        if playerA == 'Rock'and playerB == 'Paper':
            print 'PlayerB Won!'
        if playerA == 'Rock'and playerB == 'Scissors':
            print 'PlayerA Won!'
        if playerA == 'Paper' and playerB == 'Rock':
            print 'PlayerA Won!'
        if playerA == 'Paper' and playerB == 'Scissors':
            print 'PlayerB Won!'
        if playerA == 'Scissors'and playerB == 'Paper':
            print 'PlayerA Won'
        if playerA == 'Scissors'and playerB == 'Rock':
            print 'PlayerB Won'
        else:
            print 'Tie!'
    return 

RockPaperScissors ('RockPaperScissors.txt')

Tags: andiniffilenamepaperchoicesprintscissors
2条回答

Cyphase演示了如何将所需字符串放入playerA&;playerB。你知道吗

在编写程序时,最好打印输入变量,以确保它们包含预期的内容。例如,如果您在playerB= choices[-1:]行之后print playerA, playerB,那么您就会看到playerA&;playerB每个元素都有一个元素列表,而不是一个字符串。你知道吗

但是您的程序还有另一个问题:您需要更改if测试部分。如果前5if个测试中的任何一个是真的,那么将打印相应的消息,但是程序将继续进行所有其他测试。他们都是假的。这包括最后一个if测试,因此它的else部分将被执行,因此Tie!将被打印出来。你知道吗

要解决这个问题,需要将第一个后面的if变成elif,如下所示:

if playerA == 'Rock' and playerB == 'Paper':
    print 'PlayerB Won!'
elif playerA == 'Rock' and playerB == 'Scissors':
    print 'PlayerA Won!'
elif playerA == 'Paper' and playerB == 'Rock':
    print 'PlayerA Won!'
elif playerA == 'Paper' and playerB == 'Scissors':
    print 'PlayerB Won!'
elif playerA == 'Scissors' and playerB == 'Paper':
    print 'PlayerA Won'
elif playerA == 'Scissors' and playerB == 'Rock':
    print 'PlayerB Won'
else:
    print 'Tie!'

还有其他方法可以组织那些更紧凑的测试,但是这种组织方式是直截了当且易于阅读的。你知道吗

你很接近。您正在切片choices,这意味着playerAplayerB是一个元素列表。您不需要切片choices;只需按索引获取值。你知道吗

playerA = choices[0]
playerB = choices[1]

或者更好的做法是:

playerA, playerB = choices

相关问题 更多 >