Cestarian
Cestarian

Reputation: 251

Working with a while loop in classes

I'm new to working with classes, and I need to place a certain code inside a class. I've got the code working as intended outside of the class:

    minnum = 1
    maxnum = 100
    num = 1
    points = 0
    count = 9000
    while num in range(minnum, (maxnum + 1)):
        points += int(num + 300 * 2 * num / 3)
        num += 1
        if count < (points / 4):
            num -= 1
            break
    print num #Prints "19"

count should actually start at 0, but I put it to 9000 in the first example (whereas in the second I change count from 0 to 9000)

class numbers():
    def __init__(self):
        self.minnum = 1
        self.maxnum = 100
        self.num = 1
        self.points = 0
        self.count = 0
    def num(self):
        while self.num in range(self.minnum, (self.maxnum + 1)):
            self.points += int(self.num + 300 * 2 * self.num / 3)
            self.num += 1
            if self.count < (self.points / 4):
                self.num -= 1
                break
        return self.num
number = numbers()
number.count = 9000
print number.num #Prints "1"

What am I doing wrong? (I wanted print number.num to return the same value as in the first code, "19" not "1")

Upvotes: 0

Views: 106

Answers (1)

DNA
DNA

Reputation: 42617

You aren't calling the num() method in the second example, and you probably don't want to call a variable and a method by the same name ("num") either!

(As a matter of style, I'd also suggest that you initialise count via the __init__ initialiser, rather than setting count directly)

def __init__(self, count):
    self.count = count
    # etc...

number = numbers(9000)

Upvotes: 3

Related Questions