首页 > 解决方案 > 如果有这么多的可能性,如何使用 elif 或 if 条件?

问题描述

我知道有比这更聪明和简短的答案,但它并没有打印我给出的条件。您对此有解决方案吗?以及如何在循环中使用 if 语句?

import random
game = input("Do you want to play the game? yes/no")

for x in range(1):
    pc_input = random.randint(1,3)

rock = 1
paper = 2
scissors = 3

if game == "yes":
   usr_input = input("Rock , paper , scissors ")

   if pc_input == 1 and usr_input == 1:
       print("Tied game...")

   if pc_input == 1 and usr_input == 2:
       print("You won")

   if pc_input == 1 and usr_input == 3:
       print("You lost")

   if pc_input == 2 and usr_input == 1:
       print("You lost")

   if pc_input == 2 and usr_input == 2:
       print("Tied game...")

   if pc_input == 2 and usr_input == 3:
       print("You won")

   if pc_input == 3 and usr_input == 1:
       print("You won")

   if pc_input == 3 and usr_input == 2:
       print("You lost")

   if pc_input == 3 and usr_input == 3:
       print("Tied game...")

标签: pythonpython-3.x

解决方案


只有三种不同的行为,所以试着写一个if/elif只有三个分支的链。您可以简化逻辑以在相同条件下检查更多选项:

diff = (pc_input - usr_input) % 3

if diff == 0:
    print("Tied game...")

elif diff == 1:
    print("You lost")

elif diff == 2:
    print("You won")

diff是模 3 的两个数字之间的差,即如果您将 1、2、3 视为一个循环(如石头、纸、剪刀),那么模 3 的差告诉您pc_input在循环中“领先”多远,与usr_input. 领先 2 与落后 1 是一样的。


推荐阅读