如果站在一个如果?

2024-04-28 23:55:51 发布

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

Python 我该怎么做?它不会打印出来。你知道吗

if player1 == "Rock":
    if player2 == "Paper":
        print("Player 2 Wins!")
    if player2 ==  "Scissors":
        print("Player 1 Wins!")
    if player2 == "Rock":
        print("Draw")

Tags: ifpaperplayerprintdrawscissorsrockwins
2条回答

你缺少合乎逻辑的案例。你需要把玩家1和玩家2的所有情况都包括在内

if player1 == "Rock":
   if player2 == "Paper":
      print("Player 2 Wins")
   elif player2 == "Sissors":
      print("Player 1 Wins")
   elif player2 == "Rock":
      print( "Draw"):
elif player1 == "Paper":
   if player2 == "Paper":
      print("Draw")
   ...
elif player1 == "Sissors":
   if player2 == "Paper":
      print("Player 1 Wins")
   elif player2 == "Rock":
   ...

另一个简化逻辑的方法是建立一个预计算结果的字典

win = "Player 1 Wins"
loose = "Player 2 Wins"
tie = "Tie"
results = { "rock": { "paper":loose, "sissors":win, "rock":tie},
            "paper": { "paper":tie, "sissors:":win, "rock":loose},
            "sissors": { "paper":win, "sissors:":tie, "rock":loose} }

使用上面的代码,您可以按照

results["rock"]["paper"]
'Player 2 Wins'

为了完整:

if player1 == "Rock":
    if player2 == "Paper":
        print("Player 2 Wins!")
    elif player2 == "Scissors":
        print("Player 1 Wins!")
    elif player2 == "Rock":
        print("Draw")
elif player1 == "Paper":
    # Same overall format different output
elif player1 == "Scissors":
    # Same overall format different output
else:
    print("You must choose Rock, Paper, or scissors")

相关问题 更多 >