0

Running python v3.6.5 PyCharm

I have a simple for loop with an if and else statement with it:

for i in range(10):
    if i > 3 < 5:
        print(i, "first")
    else:
        print(i, "second")

The output I get is:

0 second
1 second
2 second
3 second
4 first
5 first
6 first
7 first
8 first
9 first

but shouldn't the output be:

0 second
1 second
2 second
3 second
4 first
5 second
6 second
7 second
8 second
9 second

Try it yourself. It doesn't make sense to me. Why is it doing this?

Don't really need to know

I know you might be thinking, why didn't you just say

if i == 4

but this is just a simplified problem in my program.

Thanks in advance

Hugo

Hugs
  • 91
  • 6

2 Answers2

7

A chain of operators like i > 3 < 5 is interpreted as

i > 3 and 3 < 5

where the "middle" operand(s) are repeated for the left and right operator. You want

3 < i and i < 5

, which can be abbreviated (using the reverse of the previous interpretation) as 3 < i < 5.

chepner
  • 497,756
  • 71
  • 530
  • 681
6

The correct syntax is:

if 3 < i < 5:

Be aware that Python is special here, and this construct won't work in most other languages (where you'd have to say something like 3 < i and i < 5 instead).

Thomas
  • 174,939
  • 50
  • 355
  • 478