본문 바로가기
Study Note/Python

8. Function simplification

by jhleeatl 2024. 3. 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]

 

'Study Note > Python' 카테고리의 다른 글

10. Purpose of 'while' and 'for in'  (0) 2024.04.02
9. Method vs Function / Dictionary vs List  (0) 2024.03.28
7. F-strings & Try Except  (0) 2024.03.27
6. Set & tuples and list  (0) 2024.03.27
5. Uses of [] {} ()  (0) 2024.03.26