Home > OS >  Why my for loop is not iterating all the values
Why my for loop is not iterating all the values

Time:03-02

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

CodePudding user response:

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))

CodePudding user response:

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.

  • Related