Why my for loop is not iterating all the values

Question:

When I run this code and give input as 25 it should return me its not a prime num,
But when I debug the code the range values are not iterating into if condition, only the first value of the range is passed and if its not == 0 it moves to the else part.

def find(x):
    if x > 1:
        for i in range(2,x):
            if x % i == 0:
                return "its not a prime num"
            else:
                return "Its a prime num"


user = int(input("Enter your no: "))
print(find(user))

Please help me why its working like this , I am new to programming . TIA

Asked By: judin keyzer

||

Answers:

As stated in a comment, this is an easy fix. Simply move the else statement’s return to outside of the loop.

def find(x):
    if x > 1:
        for i in range(2,x):
            if x % i == 0:
                return "its not a prime num"
        return "Its a prime num"


user = int(input("Enter your no: "))
print(find(user))
Answered By: Cresht

Using a return inside of a loop will break it and exit the function even if the iteration is still not finished. use print instead.

Answered By: Akio Saito

I discovered that for whatever reason for loops never run with the final value an easy fix is to just add 1 to the ending value.

Answered By: CRHB