Python中的简单“ if”或逻辑语句

问题:Python中的简单“ if”或逻辑语句

您将如何在Python中编写以下内容?

if key < 1 or key > 34:

我已经尝试了所有可以想到的方法,并且发现它非常令人沮丧。

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.


回答 0

如果key不是一个intfloat一个string,则需要int通过执行以下操作将其转换为第一个

key = int(key)

float做某事

key = float(key)

否则,您所遇到的问题应该可以解决,但是

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

要么

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

会更清晰一些。

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.


回答 1

这是一个布尔值:

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

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 ) ,仅当a和b均为true时为false

not (a or b) 仅当a和be均为假时才为true。

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.