DEV Community

Taeho Jeon
Taeho Jeon

Posted on

Advanced Python: for more attractive code

Tips and Tricks for Advanced Python

Python Logo

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently whereas other languages use punctuation, and it has fewer syntactical constructions than other languages.

The syntax of Python is clear, intuitive and easy to learn compared to other programming languages such as C/C++, JAVA, and Swift. Python has a lot of built-in standard features like comprehensions, dictionaries, sets, and generators to provide the most common functions required by modern programming languages. And Python also has tons of libraries provided by its own community such as 'pandas', 'numpy', 'matplotlib', and so on. Because of these, Python is one of the most popular programming languages, especially for data science.

Besides the simplicity and user-friendly of Python, learning how to write code is not an easy task. It is very similar to learn a new unfamiliar language. It needs to be practiced again and again until could feel comfortable within it. And to write more clear code, it needs to understand how Python interpreter works, but it could be out of scope for the data science. But here is seven tips and tricks for more attractive Python code as a data scientist.

1. Underscore(_) separator for Large Number

'_' can be used as a separator for expressing a large number

ten_billion = 10_000_000_000

print(f'{ten_billion:,}')
10,000,000,000

2. Assign a value with if statement

When 'if' statement has only an assignment code inside of it

# general
isHappy = True

if isHappy == True:
    result_string = 'Happy'
else:
    result_string = 'Not Happy'

print(result_string)

Happy

# advanced
isHappy = True

result_string = 'Happy' if isHappy else 'Not Happy'

print(result_string)

Happy

3. Swap values between two variable

Python can swap the values between two variable without temp variable

# general
low = 10
high = 9

if low > high:
    temp = low
    low = high
    high = temp

print(low, high)

9 10

# advanced
low = 10
high = 9

if low > high:
    low, high = high, low

print(low, high)

9 10

4. Enumerate function

If you need index value inside of for loop, use enumerate function

# general
grades = ['A', 'B', 'C', 'D', 'E', 'F']

i = 1
for grade in grades:
    print(f'{i} : {grade}')
    i += 1

1 : A
2 : B
3 : C
4 : D
5 : E
6 : F

# advanced
grades = ['A', 'B', 'C', 'D', 'E', 'F']

for i, grade in enumerate(grades, 1):
    print(f'{i} : {grade}')

1 : A
2 : B
3 : C
4 : D
5 : E
6 : F

5. List Comprehensions

a concise way to create lists

# beginner
numbers = [1, 2, 3, 4, 5, 6, 7]

squared = []
for number in numbers:
    squared.append(number * number)

print(squared)

# advanced
numbers = [1, 2, 3, 4, 5, 6, 7]

squared = [number * number for number in numbers]

print(squared)

6. Unpacking

unpacking values inside of tuples


# from 13 cards
cards = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K' )

# extract ace, 2, 3 only
ace, two, three, *_ = cards
print(ace, two, three)
A 2 3


# extract ace, [numbers], J, Q, K
ace, *numbers, J, Q, K = cards
print(ace, numbers, J, Q, K)
A ['2', '3', '4', '5', '6', '7', '8', '9', '10'] J Q K

7. For~Else

else statement also be used after for loop, it is executed after for loop

# For ~ Else
grades = ['A', 'B', 'C', 'D', 'E', 'F']

my_grade = 'A+'

for grade in grades:
    if grade == my_grade:
        print('grade found')
        break
else:
    print('grade not found')

grade not found

Top comments (11)

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!