New course! Every coder should learn Generative AI!
Try a free lesson+ 1
I really didn't get why a "while" needs an "else"??
Else after while
7 Answers
+ 9
It doesn't need an else. Can you show me the code?
+ 6
Much like superdarkec wrote, the while loop allows else statement. The statement within else gets executed only if the while condition gets False OR is False from the very beginning.
Try removing the whole if clause from the cide you submitted and see how it works then.
Bear in mind that 'else' is actually an integral part of the 'while' loop and using 'break' escapes the whole statement ('else' IS NOT executed then).
+ 3
Because there is an if statement that uses the else.
+ 2
Python allows for Else statements in while loops but they are by no means neccessary. You don't need one to write a functional while loop. But you can use one and it gets executed when the condition of the while loop becomes false.
+ 1
x=10
while x>0:
print(x)
x-=1
if x==2:
break
else:
print("done")
print("finished")
+ 1
'else' some Times do'snt obligation in 'while' fonction
0
The else belongs to the while