112

How would you write the following in Python?

if key < 1 or key > 34:

I've tried every way I can think of and am finding it very frustrating.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zak
  • 1,221
  • 2
  • 8
  • 5
  • 6
    What problem do you have? Which error do you get? Your example is valid python code in my opinion!? – Achim Aug 21 '11 at 21:14
  • Are you looking for a specific syntax? The statement you wrote about _is_ how you would write it in Python. – Yony Aug 21 '11 at 21:15

2 Answers2

226

If key isn't an int or float but a string, you need to convert it to an int first by doing

key = int(key)

or to a float by doing

key = float(key)

Otherwise, what you have in your question should work, but

if (key < 1) or (key > 34):

or

if not (1 <= key <= 34):

would be a bit clearer.

agf
  • 171,228
  • 44
  • 289
  • 238
19

Here's a Boolean thing:

if (not suffix == "flac" )  or (not suffix == "cue" ):   # WRONG! FAILS
    print  filename + ' is not a flac or cue file'

but

if not (suffix == "flac"  or suffix == "cue" ):     # CORRECT!
       print  filename + ' is not a flac or cue file'

(not a) or (not b) == not ( a and b ) , is false only if a and b are both true

not (a or b) is true only if a and be are both false.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
spikeysnack
  • 199
  • 1
  • 2