내가 한 노력들

2020- 10 -20 코딩을 할 때에는 중복되는 if문을 줄여라 본문

IT 공부/자습

2020- 10 -20 코딩을 할 때에는 중복되는 if문을 줄여라

JONGI-N CHOI 2020. 10. 20. 18:33

<수정 전>

input_line = input()
count = 0
for i in range(int(input_line)) :
    input_t = input().split(" ")
    check = input_t[0]
    del input_t[0]
    input_t = list(map(int, input_t))
    total = sum(input_t)

    if total >= 350 :
        if check == "s" :
            result = int(input_t[1]) + int(input_t[2])
            if result >= 160 :
                count += 1

        elif check == "l" :
            result = int(input_t[3]) + int(input_t[4])
            if result >= 160 :
                count += 1
print(count)

if 문을 밖으로 뺄 수 있는 것들을 밖으로 빼는 것이 좋다. 

 왜??  나중에 코드를 수정할 때에 if total >= 350 : 부분의 코딩을 수정한다고 하면, 그것을 잘 못 만지다가 아래에 모든 코드들이 동작을 안할 수 도 있다.

 

그렇기 때문에 따로 빼서 만들어주는 것이 직관성도 좋고 유지보수도 좋다!

 

 

<수정 후>

student_count = int(input())
result_count = 0

for i in range(student_count):
    student_scores = input().split(" ")
    student_subject = student_scores[0]
    student_scores = list(map(int, student_scores[1:6]))

    if sum(student_scores) < 350:
        continue

    if student_subject == 's':
        sum_subject = sum(student_scores[1:3])

    if student_subject == 'l':
        sum_subject = sum(student_scores[3:5])

    if sum_subject >= 160:
        result_count += 1
print(result_count)
if total >= 350 :
        if check == "s" :

수정전에  if안에 if가 들어가는 코딩보다.  if total >= 350 : 을 밖으로 빼서 

if sum(student_scores) < 350:
        continue

350 보다 작을 때에는 바로 if문을 빠져나가서 다음 for문으로 가도록 continue를 써서 끝내면,  그 아래 있던 if문을 밖으로 빼는 것이 가능하다. 

 

if result >= 160 :
                count += 1

그리고 각 조건마다 위 코딩이 반복되고 있기 때문에 밖으로 빼줄 수 있다. 

 

그리고 변수명도 가독성이 좋게 바꿔주는 것도 매우매우 중요하다.