Reputation: 11
I'm trying to get a program that lists out perfect numbers in a certain range.
minv= int(input('Give me a minimum value: '))
maxv= int(input('Give me a minimum value: '))
thesum = 0
perfectnums = []
for val in range(minr, maxr + 1):
for n in range(1, val):
if val % n == 0:
thesum += n
if thesum == val:
perfectnums.append(val)
print(perfectnums)
I expect 6 to pop out when I put min value at 1 and max value at 10
Upvotes: 1
Views: 180
Reputation: 363
You forgot to reset thesum
back to 0
:
minv= int(input('Give me a minimum value: '))
maxv= int(input('Give me a maximum value: '))
thesum = 0
perfectnums = []
for val in range(minv, maxv + 1):
for n in range(1, val):
if val % n == 0:
thesum += n
if thesum == val:
perfectnums.append(val)
thesum = 0
Upvotes: 0
Reputation: 631
Putting together what GaryO and Alex said, and fixing the text within the questions:
minv= int(input('Give me a minimum value: '))
maxv= int(input('Give me a maximum value: '))
perfectnums = []
for val in range(minv, maxv + 1):
thesum = 0
for n in range(1, val):
if val % n == 0:
thesum += n
if thesum == val:
perfectnums.append(val)
print(perfectnums)
Upvotes: 0
Reputation: 1065
In the first for loop you should reset the thesum
variable. Here's the working code:
minv= int(input('Give me a minimum value: '))
maxv= int(input('Give me a minimum value: '))
perfectnums = []
for val in range(minv, maxv + 1): # right variables minv and maxv
thesum = 0 # declare the variable here
for n in range(1, val):
if val % n == 0:
thesum += n
if thesum == val:
perfectnums.append(val)
print(perfectnums)
Now, for minv = 1
and maxv = 10
, You will get [6]
as result!
Upvotes: 0
Reputation: 3401
For each val you should put thesum = 0
minv= int(input('Give me a minimum value: '))
maxv= int(input('Give me a minimum value: '))
thesum = 0
perfectnums = []
for val in range(minr, maxr + 1):
# here
thesum = 0
for n in range(1, val):
if val % n == 0:
thesum += n
if thesum == val:
perfectnums.append(val)
print(perfectnums)
Upvotes: 2
Reputation: 6338
Try resetting thesum
inside the for val ...
loop. Otherwise it just grows.
(Also I assume your minv
vs minr
and maxv
vs maxr
is just a typo. Make sure those are the same.)
Upvotes: 0