-1

i am getting error in this code for checking whether a number is prime or not

m=int(input("Enter an integer: "))
factorlist=[]
x=[]
def primelist(m):
    for i in range(1,m+1):
        if m%i ==0:
            x=factorlist.append(i)
        return(x)
def isprime(m):
   return(primelist(m)==[1,m])
print(isprime(m))

I tried to execute the code to check whether a number is prime or not,i am trying to understand what is the error in the code

  • 1
    What error are you getting? Whats the values you entered? Add some details to your question. (Besides the obligatory hint "do some research on your own, StackOverflow is not for homework questions") – tistorm Mar 10 '23 at 15:21
  • 1
    Apart from the fact that *primelist(m)==[1,m]* will never be True (for any m) what error are you getting? Search stack**overflow** for '[python] prime' and you will find vast numbers of questions and answers around prime numbers – DarkKnight Mar 10 '23 at 15:29
  • This code doesn't trigger an error, it just gives an incorrect result – mozway Mar 10 '23 at 15:30
  • `x = factorlist.append(i)` doesn't do what you think it does. – chepner Mar 10 '23 at 16:12

1 Answers1

0

you are using 'return' wrongly in the for loop and you dont need x. once the for loop executed and after appending the correct results to the factorlist, then you should return whole list as below not every time in the for loop :

m=int(input("Enter an integer: "))


def primelist(m):
    factorlist=[]
    for i in range(1,m+1):
        if m%i ==0:
            factorlist.append(i)
    return factorlist
def isprime(m):
    return(primelist(m)==[1,m])
print(isprime(m))
Ugur Yigit
  • 155
  • 7
  • 1
    you should initialize `factorlist` in `primelist` to avoid weird effects as lists are mutable – mozway Mar 10 '23 at 15:47