• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Python如果语句不起作用

用户头像
it1352
帮助1

问题说明

我有一段无效的代码。

if difficulty=="Easy" or "easy" or "1":
    with  open("EasyQs.csv") as f:
        allData = [line.strip().split(",") for line in f]
        questions  = [data[0] for data in allData]
        answers = [data[1] for data in allData]
    print(questions)
if difficulty=="Hard" or "hard" or "2":
    with  open("MediumQs.csv") as f:
        allData = [line.strip().split(",") for line in f]
        questions  = [data[0] for data in allData]
        answers = [data[1] for data in allData]
    print(questions)

我尝试输入2,hard或Hard,但是它总是从 easy CSV中打印问题?
为什么?以及如何解决?

I try to type 2, hard or Hard but it always prints the questions from the 'easy' CSV? Why is this? and how can it be solved?

正确答案

#1

在Python中,如果您要检查某项是否是一组值之一,您可以使用以下方法:

In Python, if you want to check if something is one of a set of values, you use this:

if difficulty in ("Easy", "easy", "1"):






原因是您当前正在执行的操作不起作用就像您认为的那样。您具有的条件:


The reason is that what you're doing right now doesn't work like you think it does. The conditional you have:

if difficulty == "Easy" or "easy" or "1":

实际评估如下:

if (difficulty == "Easy") or ("easy") or "1":

因为是比 == 宽松的绑定运算符。因此,此总体合并条件将始终为true,因为 easy 是真实值,因此即使(difficulty == Easy)为假,运算符会将其右侧评估为true并将其返回。

Because or is a looser binding operator than ==. So this overall combined condition will always be true, because "easy" is a true value, so even if (difficulty == "Easy") is false, the or operator will evaluate its right hand side to true and return it.

这就是为什么现在您的简单案例总是会触发。

That's why right now your "easy" case always triggers.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfhckf
系列文章
更多 icon
同类精品
更多 icon
继续加载