Isn't indenting of if and else necessary in python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Isn't indenting of if and else necessary in python?

In the code given below , the if and else are in different indentation but it still works. However if I indent the else to match the it's indentation nothing prints out. Can someone say why? num = int(input("enter a number: ")) for i in range(2, int(num/2)):  if num % i  == 0:   print("not prime number") break else:  print("prime number")

17th Dec 2018, 10:58 AM
Gokul Krishna
Gokul Krishna - avatar
2 Answers
+ 7
This is an extended function of else. If you write it after a loop like this it means: If the break command is executed do operation 1; but if that doesn't happen and the loop runs through to the end, then (else) execute operation 2.
17th Dec 2018, 11:14 AM
HonFu
HonFu - avatar
+ 1
Thanks
17th Dec 2018, 11:16 AM
Gokul Krishna
Gokul Krishna - avatar