【问题标题】:Break function does not work when the elif line is true当 elif 行为真时,Break 功能不起作用
【发布时间】:2021-07-06 00:16:01
【问题描述】:
start = input('Enter quadratic equation: ')
w = start.split()
while len(w) != 7:
    start = input('Enter quadratic equation correctly: ')
    w = start.split()
while x < len(w):
        if "x" in w[x] and '^2' in w[x]:
            a = w[x]
            if a == "x^2":
                a = 1
            else:
                a = a.replace('x^2', '')
                a = int(a)
            if w[x-1] == '-':
                a = a * (-1)
            else:
                a = a
        elif 'x' in w[x] and '^' not in w[x]:
            b = w[x]
            if b == 'x':
                b = 1
            else:
                b = b.replace('x', '')
                b = int(b)
            if w[x-1] == '-':
                b = b * (-1)
            else:
                b = b
        elif w[x].isdigit() and 'x' not in w[x] and w[x] != '0':
            c = w[x]
        elif w[x] == '-' or '+' or '=':
            s = 0
        elif not w[x].isdigit() and 'x' not in w[x] and w[x] != '-' or '+' or '=':
            print('Mistake')
            break #Would not this code here work?
        x += 1  

我试过只做'else'块,但它仍然不起作用。我要做的是检查输入是否实际上是二次方程。

【问题讨论】:

  • 你能分享一下你是如何写出你的二次方程的吗?
  • 示例:3x^2 + 12x + 13 = 0

标签: python if-statement while-loop break


【解决方案1】:

错误的条件是elif not w[x].isdigit() and 'x' not in w[x] and w[x] != '-' or '+' or '=':,它不能满足你的需求


w[x] != '-' or '+' or '=': 部分:

  • 就像 (w[x]!='-') or ('+') or ('='):
  • 不喜欢 w[x] != ('-' or '+' or '='):

你想要的是w[x] not in '-+=': 和前一个一样

    elif w[x] in '-+=':
        s = 0
    elif not w[x].isdigit() and 'x' not in w[x] and w[x] not in '-+=':
        print('Mistake')
        break

【讨论】:

  • 谢谢!但是在我输入'a a a a a a'后它仍然不打印'错误'
  • @EgorK 刚刚看到之前的那个因为同样的原因是错误的,看看我的编辑
  • @EgorK 您可以考虑对答案进行投票,如果您满意,请接受它(左侧的绿色勾号);)
猜你喜欢
  • 2017-05-05
  • 1970-01-01
  • 1970-01-01
  • 2019-02-22
  • 2017-05-06
  • 1970-01-01
  • 2023-03-07
  • 2012-12-28
  • 1970-01-01
相关资源
最近更新 更多