为什么此代码的输出是:
抽屉
一场胜利
一场胜利
ERROR
而不是
抽屉
一场胜利
ERROR
ERROR
应该是什么?
为什么break不起作用,并且不为strB中不允许使用字母“T”的字符串给出结果='ERROR'? (strB ='SRTR')
def RockPaperScissors(strA,strB):
A_win = 0
B_win = 0
allowed_letters = 'SRP'
if (len(strA) != len(strB)):
result = 'ERROR'
elif (len(strA) == len(strB)):
for char in strA:
for c in strB:
if char not in allowed_letters:
result = 'ERROR'
break
elif c not in allowed_letters:
result = 'ERROR'
break
for i in range(0,len(strA)):
if (strA[i] == 'R' and strB[i] == 'S'):
a_win = 1
A_win += a_win
if (strA[i] == 'S' and strB[i] == 'P'):
a_win = 1
A_win += a_win
if (strA[i] == 'P' and strB[i] == 'R'):
a_win = 1
A_win += a_win
if (strB[i] == 'R' and strA[i] == 'S'):
b_win = 1
B_win += b_win
if (strB[i] == 'S' and strA[i] == 'P'):
b_win = 1
B_win += b_win
if (strB[i] == 'P' and strA[i] == 'R'):
b_win = 1
B_win += b_win
if A_win > B_win:
result = 'A WINS'
if B_win > A_win:
result = 'B WINS'
if A_win == B_win:
result = 'DRAW'
return result
print(RockPaperScissors('RP','PR'))
print(RockPaperScissors('PPP','RRR'))
print(RockPaperScissors('RPSR','SRTR'))
print(RockPaperScissors('RPS','RPSRP'))
答案 0 :(得分:0)
Break仅打破当前循环。你想做的不是打破,而是直接返回错误。
for char in strA:
for c in strB:
if char not in allowed_letters:
return 'ERROR'
elif c not in allowed_letters:
return 'ERROR'