0

Else Statment

The code works as it is. However, I thought the first "else" statement in the code should be indented by a tab. But then the code throws an error. Can you write the reason for this? def is_prime(num): if num > 1: for i in range(2, int(num/2)+1): if (num % i) == 0: return False break else: return True else: return False for i in range(1, 20): if is_prime(i + 1): print(i + 1, end=" ")

10th Sep 2021, 10:37 PM
Bekir
Bekir - avatar
5 Answers
+ 4
Hi Bekir! That's because it's a for-else statement not if-else. It means the else clause belongs to the for loop, not the if statement. That's why the else part doesn't match with if block. You can refer this article to understand how this statement works https://www.pythontutorial.net/JUMP_LINK__&&__python__&&__JUMP_LINK-basics/python-for-else/
11th Sep 2021, 1:50 AM
Python Learner
Python Learner - avatar
+ 1
my question was about the else state
11th Sep 2021, 12:21 AM
Bekir
Bekir - avatar
+ 1
Thanks for answer Python Learner.
11th Sep 2021, 11:07 AM
Bekir
Bekir - avatar
0
One question return False break Will code reach "break" statement?
12th Sep 2021, 8:23 AM
Rahul Yadav
Rahul Yadav - avatar
0
I think yes. if the "if" condition was false then the break command would not be reached. Return false only returend value. As far as I know it should be like this
12th Sep 2021, 9:14 AM
Bekir
Bekir - avatar