0

My code is test I'm trying to do to figure out why p & ~(p & (p - 1)) won't test for exponents of 2. anyway, the interpreter doesn't like in = 1 before the while loop for some reason.

code:

def getnumber(str):
    num=0
    for i in str:
        zz = ord(i)-48
        if zz<0 or zz>9:
            num=-1
            break
        else:
            num=(num*10)+zz
    return num

def testexp2(p):
    table = {1:1,2:2,4:3,8:4,16:5,32:6,64:7,128:8,256:9}
    if p & ~(p & (p - 1)):
        print "yes"
    else:
        print "no"


in = 1
while in is not -1:
    in = raw_input("> ")
    in = getnumber(in)
    if in>-1:
        testexp2(in)
    else:
        print "\nDone\n\n"
Imad Alazani
  • 6,688
  • 7
  • 36
  • 58
jason dancks
  • 1,152
  • 3
  • 9
  • 29

2 Answers2

5

Few problems:

  1. in is reserved keyword in python, so you can't use it as a variable name.
  2. while inp is not -1 should be while inp != -1. ( I used inp instead of in)
  3. The getnumber function can be reduced to:

Code:

def getnumber(strs):
    num = int(strs)
    return -1 if num < 0 else num
msw
  • 42,753
  • 9
  • 87
  • 112
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • @arshajii it would only work for small integers from -5 to 256, and it's a bad idea to compare integers like that. http://stackoverflow.com/questions/11476190/why-0-6-is-6-false – Ashwini Chaudhary Aug 04 '13 at 14:16
  • The small integer caching is a Cpython implementation detail and is manifestly confusing to people having trouble with the `is not` and `!=` distinction. – msw Aug 04 '13 at 14:53
  • @arshajii - even worse, it *will* work sometimes, but not others. It works when an an interning cache finds the same value, so that identity matching with `is` will work then. But that cache is just an optimization, not a language feature, so you are not guaranteed that it will always be checked when comparing ints. If you are testing for equality in ints, use '=='. – PaulMcG Aug 04 '13 at 14:54
  • @PaulMcGuire That's a good point; while in CPython it will always work, it may not work in other implementations. – arshajii Aug 04 '13 at 15:02
3

You can't declare a variable called in, that's a reserved word (or keyword) of the language, it's an operator that tests for membership. Simply rename it to something else in your code:

txt = raw_input("> ")
txt = getnumber(txt)
Óscar López
  • 232,561
  • 37
  • 312
  • 386