Study Note/Python

8. Function simplification

jhleeatl 2024. 3. 27. 16:27

Function simplification

 

The reason for simplifying functions is to make the code more concise and readable. Simplified functions reduce redundant code, decrease unnecessary complexity, and enhance maintainability. Additionally, Simplified functions can improve performance and operate more efficiently.

 

Here is an example of simplification

 

Example 1

Before

num = 3

if num % 2 == 0:
    result = 'even'
else :
    result = 'odd'

print (f' {num} is {result}')     # result = 3 is odd

 

 

After

num = 3

result = 'even' if num % 2 == 0 else 'odd'

print (f' {num} is {result}')   # result = 3 is odd

 

 

 

Example 2

Before

a_list = [1,3,2,5,1,2]

b_list = []

for a in a_list:
    b_list.append(a*2)

print (b_list)          # result = [2, 6, 4, 10, 2, 4]

 

 

After

a_list = [1,3,2,5, 1,2]
b_list = [a*2 for a in a_list ]
print(b_list)   # result = [2, 6, 4, 10, 2, 4]