Language/자료구조

튜플(Tuple) > 반복문

Sh-YE 2024. 5. 26. 15:58

1. for문

1) for문을 이용하면 튜플의 아이템을 자동으로 참조할 수 있다.

cars = '그랜져','쏘나타','말리부','카니발','쏘렌토'

#M1.인덱스
for i in range(len(cars)):
    print(cars[i])
#M2
for car in cars:
    print(car)

 

2) for문을 이용하면, 튜플 내부에 또 다른 튜플의 아이템을 조회할 수도 있다.

studentCnt = (1,19), (2,20), (3,22), (4,18), (5,21)

for i in range(len(studentCnt)):
    print('학급: {}, 학생수 : {}'.format(studentCnt[i][0],studentCnt[i][1]))
print('-'*20)

for i in studentCnt:
    print('학급: {}, 학생수 : {}'.format(i[0],i[1]))
print('-'*20)
for classNo, cnt in studentCnt:
    print('학급: {}, 학생수 : {}'.format(classNo,cnt))
    
>>>
학급: 1, 학생수 : 19
학급: 2, 학생수 : 20
학급: 3, 학생수 : 22
학급: 4, 학생수 : 18
학급: 5, 학생수 : 21
--------------------
학급: 1, 학생수 : 19
학급: 2, 학생수 : 20
학급: 3, 학생수 : 22
학급: 4, 학생수 : 18
학급: 5, 학생수 : 21
--------------------
학급: 1, 학생수 : 19
학급: 2, 학생수 : 20
학급: 3, 학생수 : 22
학급: 4, 학생수 : 18
학급: 5, 학생수 : 21

 

3) for문과 if문을 이용한 과락과목 출력.

minScore = 60

korScore = int(input('국어점수 입력 : '))
engScore = int(input('영어점수 입력 : '))
matScore = int(input('수학점수 입력 : '))
sciScore = int(input('과학점수 입력 : '))
hisScore = int(input('국사점수 입력 : '))

scores = (
    ('국어',korScore),
    ('영어',engScore),
    ('수학',matScore),
    ('과학',sciScore),
    ('국사',hisScore)
)

for sub,score in scores:
    if minScore > score:
        print(f'과락 과목 :{sub}, 점수 : {score}')

2. while문 

1) while문을 이용한 조회

 

 M1.

cars = ('그랜저','소나타','말리부','카니발','쏘렌토')

n = 0
while n < len(cars):
    print(cars[n])
    n += 1
    
>>> 
그랜저
소나타
말리부
카니발
쏘렌토

 

 M2. flag변수

cars = ('그랜저','소나타','말리부','카니발','쏘렌토')

n = 0
flag = True
while flag:
    print(cars[n])
    n += 1

    if n == len(cars):
        flag = False
        
>>>
그랜저
소나타
말리부
카니발
쏘렌토

 

 M3. break사용

n = 0
while True:
    print(cars[n])
    n += 1

    if n == len(cars):
        break
        
>>>
그랜저
소나타
말리부
카니발
쏘렌토

 

2) 튜플 내부에 또 다른 튜플의 아이템을 조회

studentCnt = (1,19), (2,20), (3,22), (4,18), (5,21)

n = 0

while n < len(studentCnt):
    print(f'{studentCnt[n][0]}학급 학생수 : {studentCnt[n][1]}')
    n += 1
    
>>>
1학급 학생수 : 19
2학급 학생수 : 20
3학급 학생수 : 22
4학급 학생수 : 18
5학급 학생수 : 21

 

3) while문과 if문을 이용해 과락과목 출력하기.

minScore = 60

korScore = int(input('국어점수 입력 : '))
engScore = int(input('영어점수 입력 : '))
matScore = int(input('수학점수 입력 : '))
sciScore = int(input('과학점수 입력 : '))
hisScore = int(input('국사점수 입력 : '))

scores = (
    ('국어',korScore),
    ('영어',engScore),
    ('수학',matScore),
    ('과학',sciScore),
    ('국사',hisScore)
)

n = 0
while n < len(scores):
    if minScore == 0 or minScore > scores[n][1]:
        print(f'과락 과목 : {scores[n][0]}, 점수 : {scores[n][1]}')
    n += 1