[Tutor] Using optional else with for loop
Manprit Singh
manpritsinghece at gmail.com
Mon Sep 28 09:00:29 EDT 2020
Dear sir ,
Consider a problem where i have to print first n prime numbers. Value of n
will be provided by the user through the keyboard. I have written the code
for this problem as given below :
def isprime(x):
for i in range(2, int(x**0.5) + 1):
if x % i == 0 :
return False
else:
return True
n = int(input("Enter a number"))
i = 2
while n > 0:
if isprime(i):
print(i)
n = n - 1
i = i + 1
Providing n = 6 through keyboard gives the answer as given below, which is
correct
2
3
5
7
11
13
My Question is regarding the function isprime() which returns True if number
is prime, else returns false . My Logic is if the number is not prime,
x % i == 0 inside the for loop will evaluate to True at some point of time.
Now return False inside if x % i == 0 will break the loop as well as it will
return False to the function call which will indicate that the number in
question is not a prime number. At this time else clause of for loop will
not work as the loop is broken due to Return False
If the number in question is a prime number, at that time the for loop will
fully operate or either will not even start(at the time when the number in
question is 2 or 3). In that case the else clause will work and return
True will indicate that the number is prime
Just need to check if my understanding is correct or not .
Regards
Manprit Singh
More information about the Tutor
mailing list