【问题标题】:if statement and for loopif 语句和 for 循环
【发布时间】:2018-11-26 21:50:22
【问题描述】:

这是我要运行的部分。它起作用了,然后它开始搞砸了。基本上它意味着迭代一个 for 循环,如果 inptype != sale 那么它意味着跳过循环的迭代并继续下一个循环。但是,当值不等于该语句时,它应该跳到 else 语句并继续,但它没有,它遵循 inptype != sale 的过程,即使值等于 sale。

这是我的代码

for row in reader:
    inpname = str(row[15])
    inptype = str(row[19])
    print(inptype)
    print (inpname)
    if not row: # if row is blank
        print("not row")
        continue# continue loop on next iteration of for loop
    elif "CUSTOMER DISCOUNT" in inpname:
        print("customer dis")
        continue
    elif inptype != "Sale" or "sale" or "SALE":
        continue
    else:

【问题讨论】:

  • 不可能说出任何带有混乱意图的东西 - 你需要解决这个问题,否则没有人可以提供帮助。另外,这东西不太可能跑了,在最后一个else:之后没有预期的块@
  • inpname 和 inptype 应该是单个字符吗?您索引行的方式只会返回一个字母。也许研究 python 字符串切片?
  • 另外,只是为了让您知道条件语句:inptype != "Sale" or "sale" or "SALE" 将永远是True。你可能想写:inptype != "Sale" and inptype != "sale" and inptype != "SALE"
  • @rammelmueller 代码运行得非常好,只要我添加了带有多个条件的 elif 语句。我显然没有正确格式化它,但其余代码已经运行了一个多月。我知道缩进完全关闭,在我的 IDLE 中它运行正常,只是当我将它粘贴到 StackOverflow 时它搞砸了

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


【解决方案1】:

第一:

inpname = str(row[15]) 获取类数组对象的索引为 16 的字段的内容,并将结果转换为字符串。因为这显然不会失败 - 您会在这里看到一个异常并报告一个完全不同的错误 - 我们可以得出结论:row 不是 None

现在看看if not row::因为row 不是None,所以continue 不会被执行。

第二:

elif inptype != "Sale" or "sale" or "SALE": 中,or 是一个布尔运算。您在这里有三个单独的术语:inptype != "Sale""sale""SALE"。最后两个术语总是评估为True,因为两个字符串都不为空。如此有效地你在这里评估(inptype != "Sale") or True or True(这可能不是你想要的,因为这总是评估为True)。因此,在继续对您的代码进行更多分析之前,请将此行改写为:

elif (inptype != "Sale") or (inptype != "sale") or (inptype != "SALE"):

【讨论】:

  • 感谢您的帮助。现在非常感谢它的工作原理!
  • 不客气!并随时接受这个答案!
猜你喜欢
  • 2013-02-06
  • 1970-01-01
  • 1970-01-01
  • 2019-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多