简体   繁体   中英

finding a list of perfect integers from a range of integer numbers

the user will input a arbitrary range where the end number is the number up to what the user wants perfect numbers from those numbers and append the numbers in a list and print the list or the list elements... Sample CODE: sum_1=0 sum_2=0 b=[]

a=range(1,int(input('enter_num_upto you want perfect num')))

for i in a:
    for items in range(1,i):
        if(i%items)==0:
            sum_1=sum_1+items
            sum_2=sum_2+items+i
        
        if sum_1==i and (sum_2//2)==i:
                   b.append(i)
               
    for j in b:
         print(j)
    

the code runs without errors but it doesn't display any outputs..... please mark my mistakes and explain the correct logics THANKS IN ADVANCE

I think the problem is that you haven't defined the list "b". I'd suggest that after you define

a=range(1,int(input('enter_num_upto you want perfect num')))

define b as

b=[]

This will tell the program that a list "b" exists, which you can then append items to. You can't append items to a list that doesn't exist yet.

The same thing should go for the 2 variables sum_1 and sum_2, you cannot define them conditionally in an "if statement", therefore you should define them at the beginning of your program, right after you define b

sum_1 = 0
sum_2 = 0

As for the logic of your code, I suggest you don't need a sum_2, after going through the for loop that makes sum_1, check if sum_1 is equal to i. But make sure whenever you use "range", you set the end as the number after you want to end it at. For example if you want the range to start at 1 and end at I, use range(1,i+1). This is only for your input. Make sure to set sum_1 back to 0 after every iteration aswell.

so:

a=range(1,int(input('enter_num_upto you want perfect num'))+1)
b=[]
sum_1=0

for i in a:
    for item in range(1,i):
       if (i%item)==0:
          sum_1= sum_1+item
     
    if sum_1==i:
        b.append(i)
    
    sum_1=0



for j in b:
   print(j)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM