这段代码中的逻辑错误? [英] Logical mistake in this code?

查看:38
本文介绍了这段代码中的逻辑错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码很简单,你一看到它就知道它做了什么.

n = int(input())如果(n%2!=0):打印奇怪"elif(n%2==0):如果(n>=2 & n<=5):打印不奇怪"elif(n>=6 & n<=20):打印奇怪"elif(n>20):打印不奇怪"

它工作正常,但仅显示 2 种情况的错误.当输入是 18 时,它说 'Not Weird' 而输出应该是 'Weird'.当输入为 20 时,也会发生同样的事情.这可能是一个愚蠢的错误或其他什么,但我似乎无法解决它,我需要有人来看看它.

解决方案

这种情况与你想象的不一样:

<预><代码>>>>n = 18>>>n >= 2 &n <= 5真的

它实际上是这样做的:

<预><代码>>>>n >= (2 & n) <= 5真的

证明:

<预><代码>>>>进口AST>>>ast.dump(ast.parse('n >= 2 & n <= 5'), annotate_fields=False)"模块([Expr(Compare(Name('n', Load()), [GtE(), LtE()], [BinOp(Num(2), BitAnd(), Name('n', Load())), Num(5)]))])">>>ast.dump(ast.parse('n >= (2 & n) <= 5'), annotate_fields=False)"模块([Expr(Compare(Name('n', Load()), [GtE(), LtE()], [BinOp(Num(2), BitAnd(), Name('n', Load())), Num(5)]))])"

关于运算符优先级的文档参考是此处.

相反,使用这个:

2 <= n <= 5

The code is simple and you will be able to tell what it does once you see it.

n = int(input())
if(n%2!=0):
    print 'Weird'
elif(n%2==0):
    if(n>=2 & n<=5):
        print 'Not Weird'
    elif(n>=6 & n<=20):
        print 'Weird'
    elif(n>20):
        print 'Not Weird'

It works fine, but it shows errors for 2 cases only. When input is 18, its says 'Not Weird' whereas the output should be 'Weird'. The same thing is happening when the input is 20. Its probably a silly mistake or something but I just can't seem to put my finger on it and I need someone to have a look at it.

解决方案

This condition doesn't do what you think it does:

>>> n = 18
>>> n >= 2 & n <= 5
True

It is actually doing this:

>>> n >= (2 & n) <= 5
True

Proof:

>>> import ast
>>> ast.dump(ast.parse('n >= 2 & n <= 5'), annotate_fields=False)
"Module([Expr(Compare(Name('n', Load()), [GtE(), LtE()], [BinOp(Num(2), BitAnd(), Name('n', Load())), Num(5)]))])"
>>> ast.dump(ast.parse('n >= (2 & n) <= 5'), annotate_fields=False)
"Module([Expr(Compare(Name('n', Load()), [GtE(), LtE()], [BinOp(Num(2), BitAnd(), Name('n', Load())), Num(5)]))])"

docs reference on operator precedence is here.

Instead, use this:

2 <= n <= 5

这篇关于这段代码中的逻辑错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆