首页 > 解决方案 > Python 3 中的 if、else 和 elif - 为什么我的 ELSE 命令总是在执行?

问题描述

尽管 3 个大型 if 语句之一为真,为什么我的 else 命令被调用。我认为只有在前面的 if/elif 语句都不为真时才会执行 ELSE,我在这里错过了什么?

import random

while True:
    computer = random.choice(["rock", "paper", "scissors"])
    user_input = "rock"

    user_input = input("Rock, Paper, or Scissors? \n Write your weapon of choice here: ")
    user_input = user_input.lower()

    if user_input == "rock":
        if computer == "rock":
            print("You both chose rock!")
        if computer == "paper":
            print("You put rock to paper, you lost!")
        if computer == "scissors":
            print("You rocked the computer's scissors, you won!")

    if user_input == "paper":
        if computer == "rock":
            print("You put paper over the computer's rock, you won!")
        if computer == "paper":
            print("You both chose paper, it's a tie!")
        if computer == "scissors":
            print("You chose paper into scissors... You lost!")

    elif user_input == "scissors":
        if computer == "rock":
            print("The computer rocked your scissors, you lost!")
        if computer == "paper":
            print("You cut up the computer's paper, you won!")
        if computer == "scissors":
            print("You both chose scissors, it's a tie!")
    else:
        print("Sorry I don't understand, please choose either 'rock' 'paper' or 'scissors'")

这是输出:

C:\Users\Darkm\PycharmProjects\TestProjects\venv\Scripts\python.exe C:/Users/Darkm/PycharmProjects/TestProjects/RockPaperScissorsGame.py
Rock, Paper, or Scissors? 
 Write your weapon of choice here: rock
You put rock to paper, you lost!
Sorry I don't understand, please choose either 'rock' 'paper' or 'scissors'
Rock, Paper, or Scissors? 
 Write your weapon of choice here: 

标签: pythonpython-3.xif-statement

解决方案


由于您有两个“if”语句,因此它被视为两个不同的块。

因此,“else”是您的第二个“if”块的一部分。

您可以将第二个“if”更改为“elif”以使其正常工作。

if user_input == "paper":

类似于:

elif user_input == "paper":

然后它将是一个块,并将给出您想要的结果。


推荐阅读