Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

RUBY

튜플 for문을 이용한 조회(파이썬) 본문

프로그래밍 언어/Python

튜플 for문을 이용한 조회(파이썬)

ruby-jieun 2023. 1. 23. 02:14

 

 

 

튜플 for문을 이용한 조회


 

 

 

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

 

 

 

 

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

 

 

 

 

 

아래 표와 튜플을 이용해서 학급별 학생 수와 전체 학생 수 그리고 평균 학생수를 출력해보자

studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)
sum = 0
avg = 0
for classNo, cnt in studentCnts:
    print('{}학급 학생수: {}명'.format(classNo, cnt))
    sum += cnt
print('전체 학생 수: {}명'.format(sum))
print('평균 학생 수: {}명'.format(sum / len(studentCnts)))
1학급 학생수: 18명
2학급 학생수: 19명
3학급 학생수: 23명
4학급 학생수: 21명
5학급 학생수: 20명
6학급 학생수: 22명
7학급 학생수: 17명
전체 학생 수: 140명
평균 학생 수: 20.0명

 

 

 

for문과 if문을 이용해서 과락 과목 출력하기

minScore = 60
scores = (
    ('국어', 58),
    ('영어', 77),
    ('수학', 89),
    ('과학', 99),
    ('국사', 50))
for item in scores:
    if item[1] < minScore:
        print('과락 과목: {}, 점수: {}'.format(item[0], item[1]))
과락 과목: 국어, 점수: 58
과락 과목: 국사, 점수: 50

 

 

 

for문과 if문을 이용해서 과락 과목 출력하기

minScore = 60
scores = (
    ('국어', 58),
    ('영어', 77),
    ('수학', 89),
    ('과학', 99),
    ('국사', 50))

for subject, score in scores:
    if score < minScore:
        print('과락 과목: {}, 점수: {}'.format(subject, score))
minScore = 60
scores = (
    ('국어', 58),
    ('영어', 77),
    ('수학', 89),
    ('과학', 99),
    ('국사', 50))

for subject, score in scores:
    if score >= minScore: continue
    print('과락 과목: {}, 점수: {}'.format(subject, score))

 

 

사용자가 국어, 영어, 수학, 과학, 국사 점수를 입력하면 과락 과목과 점수를 출력하는 프로그램을 만들어보자.

minScore = 60
korScore = int(input('국어 점수: '))
engScore = int(input('영어 점수: '))
matScore = int(input('수학 점수: '))
sciScore = int(input('과학 점수: '))
hisScore = int(input('국사 점수: '))
scores = (
    ('국어', korScore),
    ('영어', engScore),
    ('수학', matScore),
    ('과학', sciScore),
    ('국사', hisScore))
for subject, score in scores:
    if score < minScore:
        print('과락 과목: {}, 점수: {}'.format(subject, score))
국어 점수: 80
영어 점수: 59
수학 점수: 66
과학 점수: 70
국사 점수: 50
과락 과목: 영어, 점수: 59
과락 과목: 국사, 점수: 50

 

 

 

아래의 표와 튜플을 이용해서 학급 학생 수가 가장 작은 학급과 가장 많은 학급을 출력해보자

studentCnts = ((1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17))

minClassNo = 0
maxClassNo = 0
minCnt = 0
maxCnt = 0

for classNo, cnt in studentCnts:
    if minCnt == 0 or minCnt > cnt:
        minClassNo = classNo
        minCnt = cnt
    if maxCnt < cnt:
        maxClassNo = classNo
        maxCnt = cnt

print('학생 수가 가장 적은 학급(학생수): {}학급({}명)'.format(minClassNo, minCnt))
print('학생 수가 가장 많은 학급(학생수): {}학급({}명)'.format(maxClassNo, maxCnt))
학생 수가 가장 적은 학급(학생수): 7학급(17명)
학생 수가 가장 많은 학급(학생수): 3학급(23명)

 

 

Comments