-1

I'm trying to use if-function with "and". It doesn't work - is there a better way or a better command? Here is an example of my code:

        if measure >= 4.52 and <= 4.58:
            optimal += measure
            total += measure
            count += 1
        elif measure >= 4.50 and <= 4.60:
            allowed += measure
            total += measure
            count += 1
        else:
            faulty += measure
            total += measure
            count += 1

Thanks for help!

K K
  • 41
  • 5
  • 2
    There is already a perfect answer fo that. But you can skip ```and``` if you want ```elif 4.60>=measure >= 4.50 and ``` –  Aug 12 '21 at 15:28

2 Answers2

4

You need to repeat measure in your if conditions. Like so:

        if measure >= 4.52 and measure <= 4.58:
            optimal += measure
            total += measure
            count += 1
        elif measure >= 4.50 and measure <= 4.60:
            allowed += measure
            total += measure
            count += 1
        else:
            faulty += measure
            total += measure
            count += 1
alfinkel24
  • 551
  • 5
  • 13
2

The problem isn't with the if, it's with the and. Take the if out of the picture for a second:

>>> measure = 4.53
>>> measure >= 4.52 and <= 4.58
  File "<stdin>", line 1
    measure >= 4.52 and <= 4.58
                         ^
SyntaxError: invalid syntax

It's invalid because <= 4.58 on its own isn't a valid statement.

>>> measure >= 4.52 and measure <= 4.58
True

Now you have a valid boolean statement (produced by anding two other boolean statements together) that you can use in an if statement:

>>> if measure >= 4.52 and measure <= 4.58:
...     print("success!")
... 
success!

If you want to check for a value being between two other values, you don't need an and at all; you can also combine inequality operators into a single statement like this:

>>> 4.52 <= measure <= 4.58
True
Samwise
  • 68,105
  • 3
  • 30
  • 44