0
votes

I'm trying to write a python program to check if the positive integer divisable by 2 and return false or true with using classes and functions. I'm getting this error: AttributeError: 'powerOfTwo' object has no attribute 'x'. Can you help me with fixing this?

class powerOfTwo():

    def __init__(self, x):

        self.x = x

    def user(self):

        x = int(input("Enter a number: "))

    def check(self):

        if self.x == 1:

            return False

        elif (x > 0) and (x % 2 == 0):

            return True

        else:

            return False

a = powerOfTwo(5)

powerOfTwo().user()

powerOfTwo().check()
1
elif (x > 0) and (x % 2 == 0): -> self.x - h4z3

1 Answers

1
votes

Your logic of checking power of two is not correct.

Try to think about what will be the output for value 6?

Also your code returns False for value 1, but 1 is a power of 2.


You can do something like this:

class powerOfTwo():
    def __init__(self, x = 1):    # Provide a defaul value otherwise powerOfTwo().user() and powerOfTwo().check() will not work.
        self.x = x

    def user(self):               # Use self.x instead of x
        self.x = int(input("Enter a number: "))    

    def check(self):              # Use self.x instead of x
        if self.x == 0: 
            return False

        while self.x != 1:        # Updated the logic.
            if self.x % 2 != 0: 
                return False

            self.x = self.x // 2    

        return True