Python "If"+ "And"条件忽略一个。帖子中的代码

标签 python if-statement

基本上是在尝试学习 Python,我正在参加 hackerrank 30 天挑战。 任务 给定一个整数 n ,执行以下条件操作:

如果n是奇数,打印ok 如果 n 是偶数且在 2 到 5 的范围内,则打印 nok

n = 4
if n in range(2,5) and type(n/2) == int:
  print ("ok")        
else:
    print ("nok")

无论 n 是什么,它都会打印“nok”。

最佳答案

在 Python 3 中 / 总是返回一个 float (isinstance(4/2, int) is False since 4/2 返回 2.0)。

由于您实际上是在检查 n 的奇偶校验,因此请显式检查它:

... and n % 2 == 0:

关于Python "If"+ "And"条件忽略一个。帖子中的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57357054/

相关文章:

python - 在 Anaconda 中升级到 scipy 1.7?

python - Matplotlib子图内容消失使用set_xlim,set_ylim

if-statement - 当我通过管道传送到 IF 命令时会发生什么?

Python:如何在不获取 IndexError 的情况下检查不存在的列表元素的值?

c - 如何在 if 语句中指定单引号?

c++ - 使用 char 确定输出不起作用

python - ServiceNow - 如何使用 SOAP 下载报告

python - 根据列表中的元素向 Outlook 电子邮件添加多个附件

python - psycopg2.errors.InFailedSqlTransaction : current transaction is aborted, 命令被忽略,直到事务 block 结束

delphi - 在 **if 语句** 中使用 **and** 运算符