我试着拿一个文件,第一行有一个数字,它决定了有多少手石头布剪刀在玩。看起来像这样。你知道吗
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')
Cyphase演示了如何将所需字符串放入
playerA
&;playerB
。你知道吗在编写程序时,最好打印输入变量,以确保它们包含预期的内容。例如,如果您在
playerB= choices[-1:]
行之后print playerA, playerB
,那么您就会看到playerA
&;playerB
每个元素都有一个元素列表,而不是一个字符串。你知道吗但是您的程序还有另一个问题:您需要更改
if
测试部分。如果前5if
个测试中的任何一个是真的,那么将打印相应的消息,但是程序将继续进行所有其他测试。他们都是假的。这包括最后一个if
测试,因此它的else
部分将被执行,因此Tie!
将被打印出来。你知道吗要解决这个问题,需要将第一个后面的
if
变成elif
,如下所示:还有其他方法可以组织那些更紧凑的测试,但是这种组织方式是直截了当且易于阅读的。你知道吗
你很接近。您正在切片
choices
,这意味着playerA
和playerB
是一个元素列表。您不需要切片choices
;只需按索引获取值。你知道吗或者更好的做法是:
相关问题 更多 >
编程相关推荐