제로베이스 데이터 파트타임 스쿨 학습 일지 [25.03.26]

[강의 요약]

[Ch 02. 파이썬 기초 문제풀이] 강의 수강

53_조건문(01)부터 58_조건문(06)까지 강의 수강하였음

모든 연습문제 코드를 글에 포함하진 않았고

일부 코드만 가져왔다.

※ [03.27] 글을 수정하다가 이 글 수정 후 확인을 눌러서 포스팅 일자가 26일에서 27일로 변경되었음

 

 

[조건문]

강의에서 배웠던 조건문

  • if문
  • if ~ else문
  • elif문

▶ 교통 과속 위반 프로그램

  • 조건
    • 시속 50km 이하 → 안전속도 준수!!
    • 시속 50km 초과 → 안전속도 위반!! 과태료 50,000원 부과 대상!!!
carSpeed = int(input('속도 입력: '))
limitSpeed = 50

if carSpeed > 50:
    print('안전속도 위반!! 과태표 50,000원 부과 대상!!!')
else :
    print('안전속도 준수!!')

★코드 설명★

매우 기본적인 구조의 코드여서 설명할 부분은 없음

 

 

▶ 문자 메시지 길이에 따라 문자 요금이 결정되는 프로그램

  • 길이 → len() 함수 사용
message = input('메시지 입력: ')
lenMessage = len(message)
msgPrice = 50;

if lenMessage <= 50:
    msgPrice = 50
    print('SMS 발송!!')
else:
    msgPrice = 100
    print('MMS 발송!!')

print('메지지 길이: {}'.format(lenMessage))
print('메시지 발송 요금: {}원'.format(msgPrice))

★코드 설명★

 len() 함수를 사용하는데 lenMessage = len(message)로 쓴 점이 좋았다.

 

 

▶ 국어, 영어, 수학, 과학, 국사 점수를 입력하면 총점을 비롯한 각종 데이터가 출력되는 프로그램

  • 과목별 점수를 입력하면 총점, 평균, 편차를 출력한다.
    평균은 다음과 같다.
    (국어: 85, 영어: 82, 수학: 83, 과학: 75, 국사: 94)
  • 각종 편차 데이터는 막대그래프로 시각화한다.

 

korAvg = 85; engAvg = 82; matAvg = 89
sciAvg = 75; hisAvg = 94
totalAvg = korAvg + engAvg + matAvg + sciAvg + hisAvg
avgAvg = int(totalAvg / 5)

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

totalScore = korScore + engScore + matScore + sciScore + hisScore
avgScore = int(totalScore / 5)

korGap = korScore - korAvg
engGap = engScore - engAvg
matGap = matScore - matAvg
sciGap = sciScore - sciAvg
hisGap = hisScore - hisAvg

totalGap = totalScore - totalAvg
avgGap = avgScore - avgAvg

print('-' * 70)
print('총점: {}({}), 평균: {}({})'.format(totalScore, totalGap, avgScore, avgGap))
print('국어: {}({}), 영어: {}({}), 수학: {}({}), 과학: {}({}), 국사: {}({})'.format(
    korScore, korGap, engScore, engGap, matScore, matGap, sciScore, sciGap, hisScore, hisGap
))
print('-' * 70)
str = '+' if korGap > 0 else '-'
print('국어 편차: {}({})'.format(str * abs(korGap), korGap))
str = '+' if engGap > 0 else '-'
print('영어 편차: {}({})'.format(str * abs(engGap), engGap))
str = '+' if matGap > 0 else '-'
print('수학 편차: {}({})'.format(str * abs(matGap), matGap))
str = '+' if sciGap > 0 else '-'
print('과학 편차: {}({})'.format(str * abs(sciGap), sciGap))
str = '+' if hisGap > 0 else '-'
print('국사 편차: {}({})'.format(str * abs(hisGap), hisGap))
str = '+' if totalGap > 0 else '-'
print('총점 편차: {}({})'.format(str * abs(totalGap), totalGap))
str = '+' if avgGap > 0 else '-'
print('평균 편차: {}({})'.format(str * abs(avgGap), avgGap))
print('-' * 70)

★코드 설명★

이걸 코드로 작성하려면 먼저 이해력이 좋아야 할 것 같다.

어려운 코드는 아닌데 의외로 길고 복잡함

간단하게 순서의 흐름으로 설명해보겠음

  1. 조건으로 주어진 각 과목별 평균점수를 변수로 선언
  2. 점수 5개 입력받음
  3. 총점과 평균 계산
  4. 편차 계산(입력받은 점수가 평균보다 얼마나 차이 나는지)
  5. 값 출력
  6. 편차를 막대그래프로 표현(+와 -로)

 

 

▶ 난수를 이용해서 홀/짝 게임 만들기

import random

comNum = random.randint(1, 2)
userSelect = int(input('홀/짝 선택: 1.홀 \t 2.짝 '))

if comNum == 1 and userSelect == 1:
    print('빙고!! 홀수!!!')
elif comNum == 2 and userSelect == 2:
    print('빙고!! 짝수!!!')
elif comNum == 1 and userSelect == 2:
    print('실패!! 홀수!!!')
elif comNum == 2 and userSelect == 1:
    print('실패!! 짝수!!!')


comNumber = random.randint(1, 3)
userNumber = int(input('가위,바위,보 선택: 1.가위 \t 2.바위 \t 3.보 '))

if (comNumber == 1 and userNumber == 2) or \
        (comNumber == 2 and userNumber == 3) or \
        (comNumber == 3 and userNumber == 1):
    print('컴퓨터: 패, 유저: 승')
elif comNumber == userNumber:
    print('무승부')
else:
    print('컴퓨터: 승, 유저: 패')

print('컴퓨터: {}, 유저: {}'.format(comNumber, userNumber))

★코드 설명★

random 모듈을 사용해서 난수를 생성함

먼저 import를 통해 random 모듈을 불러옴

사용 방법은 다음과 같음

  • random.randint(a,b)
    • a부터 b 사이의 정수 중 무작위로 1개 반환(양 끝 포함)
  • random.random()
    • 0.0 이상 1.0 미만의 실수 중 무작위 반환
  • random.uniform(a,b)
    • a부터 b 사이의 실수를 랜덤으로 선택
  • random.choice(리스트)
    • 리스트 또는 튜플 등 안에서 무작위로 하나 선택
  • random.choices(리스트, k=n)
    • 리스트 안에서 중복 허용하며 n개 뽑기
  • random.sample(리스트, k=n)
    • 리스트 안에서 중복 없이 n개 뽑기
  • random.shuffle(리스트)
    • 리스트의 순서를 무작위로 섞기(원본 변경되니 주의)

 

코드 예시는 다음과 같음

import random

# random.randint(a, b)
num = random.randint(1, 6)  # 1~6 주사위 굴리기
print(num)	# 4


# random.random()
num = random.random()
print(num)	# 0.723381


# random.uniform(a, b)
num = random.uniform(1.5, 9.5)
print(num)	# 3.84237


# random.choice(리스트)
menu = ['피자', '햄버거', '샐러드', '김밥']
lunch = random.choice(menu)
print('오늘 점심은:', lunch)	# 오늘 점심은: 샐러드


# random.choices(리스트, k=n)
lotto = random.choices(range(1, 46), k=6)
print(lotto)	# [5, 17, 17, 33, 2, 41]


# random.sample(리스트, k=n)
lotto = random.sample(range(1, 46), k=6)
print(lotto)	# [7, 23, 39, 2, 18, 42]


# random.shuffle(리스트)
cards = ['A', '2', '3', '4', '5']
random.shuffle(cards)
print(cards)	# ['3', 'A', '5', '2', '4']

 

 

 

[나의 생각 정리]

  • 조건문 연습문제 강의에서 일부 코드를 가져와서 사용된 모듈을 살펴봤다.

 

[적용점]

  • 난수 생성하는 모듈은 코테 문제에서 몇 번 사용한 경험이 있다.
  • 물론 조건문의 사용빈도가 훨씬 높다.

 

 

 

“이 글은 제로베이스 데이터 스쿨 주 3일반 강의 자료 일부를 발췌하여 작성되었습니다.”