为什么我会收到语法错误?

Rya*_*yan 0 python if-statement

sales = 1000

#def commissionRate():  

if (sales < 10000):
    print("da")  
else:
    if (sales <= 10000 and >= 15000):
        print("ea")
Run Code Online (Sandbox Code Playgroud)

if (sales <= 10000 and >= 15000):行上的语法错误.特别是在等号上.

EdC*_*ica 6

您还需要sales与第二个条件进行比较:

In [326]:

sales = 1000
?
#def commissionRate():
?
?
if (sales < 10000):
    print("da")
else:
    if (sales <= 10000 and sales >= 15000):
        print("ea")
da
Run Code Online (Sandbox Code Playgroud)

你需要这个:

if (sales <= 10000 and sales >= 15000):
                       ^^^^ sales here
Run Code Online (Sandbox Code Playgroud)

此外,您不需要()围绕if条件使用括号:

if sales <= 10000 and sales >= 15000:
Run Code Online (Sandbox Code Playgroud)

工作良好

您可以将其重写为更紧凑:

In [328]:

sales = 1000
?
if sales < 10000:
    print("da")
else:
    if 10000 <= sales <= 15000:
        print("ea")
da
Run Code Online (Sandbox Code Playgroud)

所以if 10000 <= sales <= 15000:也有效,谢谢@Donkey Kong

另外(感谢@pjz)与代码无关,逻辑上销售不能小于10000且大于15000.

因此,即使没有语法错误,条件也永远不会True.

你想要if sales > 10000 and sales <= 15000:if 10000 <= sales <= 15000:哪个可能更清楚

只是为了扩展if 10000 <= sales <= 15000:语法(感谢@will的建议),在python中可以执行数学比较,这里lower_limit < x < upper_limit也解释比通常更自然的数学比较if x > lower_limit and x < upper_limit:.

这允许从文档链接比较:

形式上,如果a,b,c,..., y,z是表达式并且op1,op2,...,opN 是比较操作符,则a op1 b op2 c ... y opN z等同于a op1 b and b op2 c and ... y opN z,除了每个表达在评价最多一次.

  • 值得一提的是`if(10000 <= sales <= 15000)`也许? (4认同)