I recently wrote a program to determine perfect numbers.....

n=raw_input("Please input a number: ")
factors = []
p=int(n)
for k in range(1):
    x=0
    while x < p-(p/3):
        x=x+1
        z = p/x
        if p%z == 0:
            factors.append(z)
            if factors.count(z) > 1:
                factors.remove(z)

print "The factors are,", factors
print "the sum of the factors is", sum(factors)

if sum(factors) == 2*p:
    print "Therefore,", p ,"is a perfect number as the \nsum of its factors is twice itself."

else:
    print "Therefore,", p ,"is not a perfect number"

It works fine.....
Yet when I modify it ever so slightly to calculate every perfect number up to a certain value,

n=raw_input("Please input a number up to which the computer \n will calculate perfect numbers: ")
factors = []
p=int(n)
t=0
while t <= p:
    t=t+1
    for k in range(1):
        x=0
        while x < t :
            x=x+1
            z = t/x
            if t%z == 0:
                factors.append(z)
                if factors.count(z) > 1:
                    factors.remove(z)

    if sum(factors) == 2*t:
        print  t ,"is a perfect number as the sum of its factors is twice itself."
        print "The factors are,", factors
        print "the sum of the factors is", sum(factors)

I get this reply from python...

3 is a perfect number as the sum of its factors is twice itself.
The factors are, [2, 3, 1]
the sum of the factors is 6

Whats going on??

don't you need to empty the factors array before you start factoring the next number?

Try factors=[] just before the for k in range(1):

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.