python - 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:
解决方案
由于您有两个“if”语句,因此它被视为两个不同的块。
因此,“else”是您的第二个“if”块的一部分。
您可以将第二个“if”更改为“elif”以使其正常工作。
if user_input == "paper":
类似于:
elif user_input == "paper":
然后它将是一个块,并将给出您想要的结果。
推荐阅读
- django - django 如何从 django datetime.date 类中减去日期
- typescript - 如何设置量角器以显示测试失败的行
- arrays - 使用两个参数\参数过滤
- javascript - 在@Component 中使用导入的模块
- javascript - 非常基本的出现和消失文本(几乎完成)
- java - 使用 Java Stream 将 map 方法的参数添加到 foreach 方法
- android - 如何从物理设备获取 UTC 时区偏移量(如 UTC+07:00)?
- vue.js - vuejs 错误修复调试/部署查询
- python - 如何创建具有衍生进程的 MPI 组?
- javascript - 与 include 一起使用时,Sequelize 返回空值