Skip to content
Advertisement

Why my for loop is not iterating all the values

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

Advertisement

Answer

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))
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement