DEV Community

Advanced Python: for more attractive code

Taeho Jeon on May 20, 2019

Tips and Tricks for Advanced Python Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is...
Collapse
 
detinsley1s profile image
Daniel Tinsley

I think it depends on how complicated the comprehension or the ternary expression is. If it's hard to comprehend, then a loop or an if...elif...else statement would be better, but if it's a simple statement, then a comprehension or ternary expression is just as good and is more Pythonic.

Collapse
 
mangrobangit profile image
werlindo

Thank you! Very helpful!!

Collapse
 
teosoft7 profile image
Taeho Jeon

WIth my pleasure~~~

Collapse
 
burdier profile image
Burdier

I agree with you.

Collapse
 
mx profile image
Maxime Moreau

Hi, thanks for sharing :)

"else statement also be used after for loop, it is executed after for loop", but why it could be needed? Just put some code after the for loop do the job, nop?

Collapse
 
detinsley1s profile image
Daniel Tinsley

The 'else' is used if the loop completes successfully, so if the loop ends early, such as by using a 'break' statement, the 'else' won't run. It's just an easier way to run code if and only if the loop finishes successfully without needing to use a flag variable to detect whether the loop finishes.

With flag:

flag = True
for i in range(10):
    if i == 8:
        flag = False
if flag:
    print('Loop completed') # won't print, since flag is False

With 'else':

for i in range(10):
    if i == 8:
        break
else:
    print('Loop completed') # won't print since the loop ended early

In both cases, the text won't print, since the loop didn't complete. However, if the loops did complete, then the text would print.

Collapse
 
mx profile image
Maxime Moreau

Hi, well thank a ton! :)

Collapse
 
teosoft7 profile image
Taeho Jeon

Hi, you're welcome.

else: after for loop confirms the for loop is finished, not confirms the exit of the loop.

else: does not be executed when it is exited by 'break' statement.

Collapse
 
teosoft7 profile image
Taeho Jeon

Thanks for the feedback. I agree with you.

Collapse
 
voidjuneau profile image
Juneau Lim

Wow, I know only half of them. Thanks for the great tips!

Collapse
 
teosoft7 profile image
Taeho Jeon

You're welcome!