Python简单if或逻辑语句

Zak*_*Zak 99 python logic if-statement

你会怎么写,在python中:

if key < 1 or key > 34:
Run Code Online (Sandbox Code Playgroud)

我已经尝试过各种我能想到的方式,并且发现它非常令人沮丧.

agf*_*agf 202

如果key不是int或者float而是strING,你需要将其转换为int做第一

key = int(key)
Run Code Online (Sandbox Code Playgroud)

float通过做

key = float(key)
Run Code Online (Sandbox Code Playgroud)

否则,你问题中的内容应该有效,但是

if (key < 1) or (key > 34):
Run Code Online (Sandbox Code Playgroud)

要么

if not (1 <= key <= 34):
Run Code Online (Sandbox Code Playgroud)

会更清楚一些.

  • 谢谢,我忘记了虽然有数字,但键实际上是一个字符串。很抱歉在网站上发布了一个愚蠢的第一篇文章。在发布之前,请尝试并努力解决我的问题。 (2认同)

小智 17

这是一个布尔值:

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

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

(not a) or (not b) == not ( a and b ) ,只有当a和b都为真时才是假的

not (a or b) 只有当a和be都是假的时候才是真的.