for -- else: what was the motivation?

Jach Feng jfong at ms4.hinet.net
Sat Oct 8 22:33:07 EDT 2022


Axy 在 2022年10月8日 星期六上午11:39:44 [UTC+8] 的信中寫道:
> Hi there, 
> 
> this is rather a philosophical question, but I assume I miss something. 
> I don't remember I ever used else clause for years I was with python and 
> my expectation was it executed only if the the main body was never run. 
> Ha-ha! I was caught by this mental trap. 
> 
> So, seriously, why they needed else if the following pieces produce same 
> result? Does anyone know or remember their motivation? 
> 
> Just curious. 
> 
> Axy. 
> 
> print('--- with else') 
> 
> 
> for i in [1,2,3]: 
>     print(i) 
> else: 
>     print(4) 
> 
> for i in []: 
>     print(i) 
> else: 
>     print(5) 
> 
> print('--- without else') 
> 
> for i in [1,2,3]: 
>     print(i) 
> print(4) 
> 
> for i in []: 
>     print(i) 
> print(5)
The else is always coming with the break, not the for. There are [for ...], [for...break...], and[for...break...else], but the [for...else] is insane.

--Jach


More information about the Python-list mailing list