Python 3中的if,else和elif-为什么我的ELSE命令总是执行?

时间:2019-11-11 07:21:44

标签: python python-3.x if-statement

尽管if语句为3个大的真值之一,为什么我的else命令却被调用。我以为ELSE仅在先前的if / elif语句都不为真时才执行,我在这里错过了什么?

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: 

3 个答案:

答案 0 :(得分:0)

由于您有两个'if'语句,因此将其视为两个不同的块。

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

您可以将第二个'if'更改为'elif'以使其起作用。

if user_input == "paper":

类似于:

elif user_input == "paper":

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

答案 1 :(得分:0)

if user_input == "rock"与以下if - elif - else不相关,因此即使为else也将被执行。更改

if user_input == "paper"

elif user_input == "paper"

答案 2 :(得分:0)

用elif替换第二个if语句,它应该可以正常工作: REPL