I want to make a pattern about finding perfect number. This number is; the sum of its divisors must be equal to itself Actually I don't know what is exact problem about. On line 9 it shows my code as wrong.
sayi = int(input("enter a number: "))
bolenler = list()
bolenler = range(0,sayi-1)
bolensayi = list()
toplam = 0
for i in bolenler:
if(sayi % i == 0):
bolensayi.append(i)
for i in bolensayi:
toplam = i
if(toplam == sayi):
print("that number is a perfect number")
else:
print("that number is not a perfect number")
giving that error:
sayınızı giriniz: 6
Traceback (most recent call last):
File "/home/cagan/Desktop/Python Scratch/mükemmelSayi.py", line 9, in <module>
if(sayi % i == 0):
ZeroDivisionError: integer division or modulo by zero
Process finished with exit code 1
CodePudding user response:
The reason that you are getting that error is because you cannot divide or modulo a number by zero in python. That error is fixed like so:
sayi = int(input("enter a number: "))
bolenler = list()
bolenler = range(1,sayi-1)
bolensayi = list()
toplam = 0
for i in bolenler:
if(sayi % i == 0):
bolensayi.append(i)
for i in bolensayi:
toplam = i
if(toplam == sayi):
print("that number is a perfect number")
else:
print("that number is not a perfect number")
All I did was change the value of bolenler
from range(0,sayi-1)
to range(1,sayi-1)
You can also make your code a lot shorter like so:
sayi = int(input("enter a number: "))
toplam = sum([i for i in range(1, sayi-1) if sayi % i == 0])
if(toplam == sayi):
print("that number is a perfect number")
else:
print("that number is not a perfect number")
CodePudding user response:
As mentioned in the built-in exceptions, you can't have the second argument as 0. the variable bolenler
that you're looping over begins with 0. Initiating the variable as bolenler = range(1,sayi-1)
should fix it.