我应该创建一个链式条件或嵌套?
player1 = raw_input ("?")
player2 = raw_input ("?")
if (player1 == 'rock' and player2 == 'scissors'):
print "Player 1 wins."
elif (player1 == 'rock' and player2 == 'rock'):
print "Tie"
elif (player1 == 'scissors' and player2 == 'paper'):
print "Player 1 wins."
elif (player2 == 'scissors' and player2 == 'scissors'):
print "Tie"
elif (player1 == 'paper' and player2 == 'paper'):
print "Tie"
elif (player1 == 'paper' and player2 == 'scissors'):
print "Player 2 wins."
elif (player1 == 'rock'and player2 == 'paper'):
print "Player 2 wins."
elif (player1 == 'paper' and player2 == 'rock'):
print "Player 2 wins."
elif (player1 == 'scissors' and player2 == 'rock'):
print "Player 2 wins."
else:
print "This is not a valid object selection."
答案 0 :(得分:0)
这个问题可能应该迁移到CodeReview,但在此之前,我会把答案放在这里......
您可以使用or
组合产生相同结果的不同条件,而不是将所有这些检查嵌套在或链接中,例如,一名球员获胜。另外,检查玩家1是否胜过玩家2也是相反的,所以你可以把它放到一个函数中。
这将使您的代码更短,更易读,更易于维护。
ROCK, PAPER, SCISSORS = "rock", "paper", "scissors"
def valid(s):
""" s is a valid input """
return s in [ROCK, PAPER, SCISSORS]
def wins(p1, p2):
""" p1 wins over p2 """
return (p1 == ROCK and p2 == SCISSORS or
p1 == SCISSORS and p2 == PAPER or
p1 == PAPER and p2 == ROCK)
player1 = raw_input ("Player 1: ").strip().lower()
player2 = raw_input ("Player 2: ").strip().lower()
if valid(player1) and valid(player2):
if wins(player1, player2):
print "Player 1 wins."
elif wins(player2, player1):
print "Player 2 wins."
else:
print "Tie."
else:
print "This is not a valid object selection."