Hello today i wanna share about for ...else loop:
example: finding prime numbers
ans = int(input("number:"))
if ans >1:
for i in range(2,ans):
if ans%i==0:
print(f'{ans} is not a prime number')
break
else:
print(f'{ans} is a prime number.')
else:
print(f"{ans} is not a prime number")
What is for else loop?
when for loop hasn't been broke, else will happen
In this case:
I am trying to find prime number, so if ans is larger than 1(to make sure it isn't negative),
i will arrange a for loop, which let the range of 2 to ans(not include ans) to be divided by ans itself
If remaining value can be divided, then it is not a prime number, and the for loop will be break
if the for loop has not been broken, which means nothing can divide ans and get 0 remaining value
then it's a prime number, else will occur and print it's prime number
example: finding prime numbers
ans = int(input("number:"))
if ans >1:
for i in range(2,ans):
if ans%i==0:
print(f'{ans} is not a prime number')
break
else:
print(f'{ans} is a prime number.')
else:
print(f"{ans} is not a prime number")
What is for else loop?
when for loop hasn't been broke, else will happen
In this case:
I am trying to find prime number, so if ans is larger than 1(to make sure it isn't negative),
i will arrange a for loop, which let the range of 2 to ans(not include ans) to be divided by ans itself
If remaining value can be divided, then it is not a prime number, and the for loop will be break
if the for loop has not been broken, which means nothing can divide ans and get 0 remaining value
then it's a prime number, else will occur and print it's prime number