티스토리 뷰

5명의 점수를 차례대로 입력받아, list 에 추가(append) 한다.  loop 후에 평균값을 구하고 평균미만인 학생수를 구해본다.

scores = []

for i in range(5):
    score = input('학생 점수를 입력하세요.')
    scores.append(int(score))

# 평균구하기
avg = sum(scores) / len(scores)

# 평균이하 학생수
cnt = 0

for s in scores:
    if s < avg:
        cnt += 1

print("평균점수 : ", avg)
print("평균점수이하 학생수 : ", cnt)

 

여기서 4줄로 구현한 평균미만 학생수 로직을 한줄로 줄일 수가 있다. 

cnt = 0
for s in scores:
    if s < avg:
        cnt += 1
# 한 줄로 줄이기.
cnt = sum([1 for s in scores if s < avg])

 

python document 에서는 아래 링크에서 내용을 더 참고할 수 있다.

 

5. Data Structures — Python 3.10.4 documentation

5. Data Structures This chapter describes some things you’ve learned about already in more detail, and adds some new things as well. 5.1. More on Lists The list data type has some more methods. Here are all of the methods of list objects: list.append(x) 

docs.python.org

# (참고) 문자열 중간에 특정 문자열을 삽입하고 싶을때,
str = input('문자열을 입력하세요 : ') # hello
print('-'.join(str)) # h-e-l-l-o
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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 29 30
글 보관함