简体   繁体   English

为什么 <= 在 Python 中抛出无效的语法错误

[英]Why is <= throwing an invalid syntax error in Python

I am very new to Python.我对 Python 很陌生。 I'm trying to create a loop that compares int, between a range.我正在尝试创建一个循环,在一个范围之间比较 int。

while counter < N:
     x = randn()
     if x >= 0 and <=1:
        print('0-1')
        counter = counter + 1

     elif x < 0 and < -1
        print("0- -1")

    counter = counter + 1

I keep getting a syntax error on the <=我在<=上不断收到语法错误

  File "<ipython-input-35-1d74b6e80ea0>", line 9
if x >= 0 and <=1:
               ^

SyntaxError: invalid syntax语法错误:无效语法

Any help on what I am missing would be greatly appreciated对我所缺少的任何帮助将不胜感激

The correct syntax is:正确的语法是:

if x >= 0 and x <= 1:

The reason for your confusion is because you're writing it out as you would explain it to a person.你困惑的原因是因为你写出来就像你向别人解释一样。 X has to larger or equal to zero and smaller or equal to one. X 必须大于或等于 0 且小于或等于 1。

In python however, these are two separate conditions , which need to be written out in full: x >= 0 and also x <= 1 .然而,在 python 中,这是两个独立的条件,需要完整地写出: x >= 0x <= 1

Alternatively , you have the option of combining the operators into a single condition like so:或者,您可以选择将运算符组合成一个条件,如下所示:

if 0 <= x <= 1

Merging them this way turns the inequality into a single (compound) condition.以这种方式合并它们会将不等式转化为单一(复合)条件。

Replace代替

x >= 0 and <=1

by经过

x >= 0 and x<=1

You should try writing it as if x >= 0 and x <= 1: .你应该试着把它写成if x >= 0 and x <= 1: The and connects two separate statements, so you need to write the comparisons separately. and连接两个单独的语句,因此您需要单独编写比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM