简体   繁体   中英

Why is <= throwing an invalid syntax error in Python

I am very new to Python. I'm trying to create a loop that compares int, between a range.

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.

In python however, these are two separate conditions , which need to be written out in full: x >= 0 and also x <= 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: . The and connects two separate statements, so you need to write the comparisons separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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