Logical mistake in this code?

白昼怎懂夜的黑 提交于 2019-12-08 12:18:07

问题


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.


回答1:


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



回答2:


Just slightly modified your code getting rid of & . You can combine the range in the if/elif statement

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



回答3:


Change the operator & to and. & is a bitwise operator.



来源:https://stackoverflow.com/questions/51621665/logical-mistake-in-this-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!