jason dancks
jason dancks

Reputation: 1142

python: how do I do simple variable declaration?

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"

Upvotes: 0

Views: 116

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250871

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

Upvotes: 5

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 235984

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)

Upvotes: 3

Related Questions