[데이터스쿨] 파이썬 기초 문제풀이

이주희·2022년 12월 7일
0

오늘의 날짜와 현재 시간을 출력해보자.

import datetime

today = datetime.datetime.today()
print(today)

2022-12-07 09:34:33.332651


데이터와 변수

'주문확인서' 템플릿을 만들어보자.

name = '홍길동'
product = '야구글러브'
orderNo = 2568956
payMethod = '신용카드'
productPrice = 110000
payPrice = 100000
usePoint = 10000
payDate = '2021/08/03 21:50:12'
payDiv= 6
payDivcategory = '무'
phnoe = '02-1234-5678'

print(name, '고객님 안녕하세요.')
print(name, '고객님의 주문이 완료되었습니다.')
print('다음은 주문건에 대한 상세 내역입니다.')
print('-' * 50)
print('상품명\t: ', product)
print('주문번호\t: ', orderNo)
print('결제방법\t: ', payMethod)
print('상품금액\t: ', productPrice)
print('결제금액\t: ', payPrice)
print('포인트\t: ', usePoint)
print('결제일시\t: ', payDate)
print('할부\t\t: ', payDiv)
print('할부유형\t: ', payDivcategory)
print('문의\t\t: ', phnoe)
print('-' * 50)
print('저희 사이트를 이용해주셔서 감사합니다.')
홍길동 고객님의 주문이 완료되었습니다.
다음은 주문건에 대한 상세 내역입니다.
--------------------------------------------------
상품명	:  야구글러브
주문번호	:  2568956
결제방법	:  신용카드
상품금액	:  110000
결제금액	:  100000
포인트	:  10000
결제일시	:  2021/08/03 21:50:12
할부		:  6
할부유형	:  무
문의		:  02-1234-5678
--------------------------------------------------
저희 사이트를 이용해주셔서 감사합니다.
저희 사이트를 이용해주셔서 감사합니다.

원의 반지름을 입력 시 넓이와 둘레를 출력해보자.

pi = 3.14
radius = float(input('반지름(cm) 입력: '))

circleArea = pi * radius * radius
circleLength = 2 * pi * radius

print('원의 넓이: %d' % circleArea)
print('원의 둘레: %d' % circleLength)

print('원의 넓이: %.1f' % circleArea)
print('원의 둘레: %.1f' % circleLength)
반지름(cm) 입력: 3
원의 넓이: 28
원의 둘레: 18
원의 넓이: 28.3
원의 둘레: 18.8

입력받은 개인정보를 포맷문자열을 이용하여 출력해보자.

name = input('이름 입력: ')
mail = input('메일 입력: ')
id = input('아이디 입력: ')
pw = input('비밀번호 입력: ')
privateNumber1 = input('주민번호 앞자리 입력: ')
privateNumber2 = input('주민번호 뒷자리 입력: ')
address = input('주소 입력: ')

print('-' * 30)
print(f'이름 : {name}')
print(f'메일 : {mail}')
print(f'아이디 : {id}')

pwStar = '*' * len(pw)
print(f'비밀번호 : {pwStar}')

privateNumberStar = privateNumber2[0] + ('*' * 6)
print(f'주민번호 : {privateNumber1} - {privateNumberStar}')
print(f'주소 : {address}')
print('-' * 30)
이름 입력: hong gil dong
메일 입력: hong@gmail.com
아이디 입력: hongID
비밀번호 입력: 12345678
주민번호 앞자리 입력: 840921
주민번호 뒷자리 입력: 2018543
주소 입력: korea seoul
------------------------------
이름 : hong gil dong
메일 : hong@gmail.com
아이디 : hongID
비밀번호 : ********
주민번호 : 840921 - 2******
주소 : korea seoul
------------------------------

체중(g)과 신장(cm)을 입력하면 BMI지수가 출력되는 프로그램을 만들어보자.

isdigit()
숫자인지 확인 (숫자이면 True, 아니면 Flase)

height = input('신장 입력(cm): ')
weight = input('체중 입력(g): ')

if height.isdigit():
    height = int(height) / 100

if weight.isdigit():
    weight = int(weight) / 10

print('체중 : {}kg'.format(weight))
print('신장 : {}m'.format(height))

bmi = weight / (height * height)
print('BMI : %.2f' % bmi)
신장 입력(cm): 165
체중 입력(g): 500
체중 : 50.0kg
신장 : 1.65m
BMI : 18.37

num1과 num2의 값을 서로 바꾸고 각각 출력해보자.

num1 = 10
num2 = 20
print('num1: {}, num2: {}'.format(num1, num2))

a = num1
num1 = num2
num2 = a
print('num1: {}, num2: {}'.format(num1, num2))
num1: 10, num2: 20
num1: 20, num2: 10

중간, 기말고사 점수 입력 시 총점과 평균이 출력되는 프로그램을 만들어보자.

score1 = input('중간고사 점수: ')
score2 = input('기말고사 점수: ')

if score1.isdigit() and score2.isdigit():
    score1 = int(score1)
    score2 = int(score2)

    totalScore = score1 + score2
    avgScore = totalScore / 2

    print('총점: {}, 평균: {}'.format(totalScore, avgScore))

else:
    print('잘못 입력하셨습니다.')
중간고사 점수: 100
기말고사 점수: 80
총점: 180, 평균: 90.0

키오스크에서 사용하는 언어 선택 프로그램을 만들어보자.

selectNumber = input('언어 선택(choosa your languge): 1. 한국어 \t 2. English')

if selectNumber == '1':
    menu = '1.샌드위치 \t 2. 햄버거 \t 3. 주스 \t 4. 커피 \t 5.아이스크림'
elif selectNumber == '2':
    menu = '1.Snadwich \t 2. Hamburger \t 3. juice \t 4. Coffee \t 5.Ice cream'

print(menu)
#'1'선택 시
언어 선택(choosa your languge): 1. 한국어 	 2. English
1.샌드위치 	 2. 햄버거 	 3. 주스 	 4. 커피 	 5.아이스크림

#'2'선택 시
언어 선택(choosa your languge): 1. 한국어 	 2. English
1.Snadwich 	 2. Hamburger 	 3. juice 	 4. Coffee 	 5.Ice cream

내 나이가 100살이 되는 해의 연도를 구하는 프로그램을 만들어보자.

import datetime

today = datetime.datetime.today()

myAge = input('나이입력:')
if myAge.isdigit():
    afterAge = 100 - int(myAge)
    myHundred = today.year + afterAge

    print('{}년({}년후)에 100살!!'.format(myHundred,afterAge ))
else:
    print('잘못 입력했습니다.')
나이입력:20
2102년(80년후)에 100살!!

연산자

거스름돈을 계산하는 프로그램을 만들어 보자.

(단, 거스름돈은 지폐와 동전의 개수를 최소로 하고, 1원단위 절사한다.)

money50000 = 50000; money10000 = 10000; money5000 = 5000; money1000 = 1000
money500 = 500; money100 = 100; money50 = 50; money10 = 10

money50000Cnt = 0; money10000Cnt = 0; money5000Cnt = 0; money1000Cnt = 0
money500Cnt = 0; money100Cnt = 0; money50Cnt = 0; money10Cnt = 0

productPrice = int(input('상품 가격 입력: '))
payPrice = int(input('지불 금액: '))

if payPrice > productPrice:
    changeMoney = payPrice - productPrice
    changeMoney = (changeMoney//10) * 10
    print('거스름 돈: {}(원단위 절사)'.format(changeMoney))

if changeMoney > money50000:
    money10000Cnt = changeMoney // money50000
    changeMoney %= money50000

if changeMoney > money10000:
    money10000Cnt = changeMoney // money10000
    changeMoney %= money10000

if changeMoney > money5000:
    money5000Cnt = changeMoney // money5000
    changeMoney %= money5000

if changeMoney > money1000:
    money1000Cnt = changeMoney // money1000
    changeMoney %= money1000

if changeMoney > money500:
    money500Cnt = changeMoney // money500
    changeMoney %= money500

if changeMoney > money100:
    money100Cnt = changeMoney // money100
    changeMoney %= money100

if changeMoney > money50:
    money100Cnt = changeMoney // money50
    changeMoney %= money50

if changeMoney > money10:
    money10Cnt = changeMoney // money10
    changeMoney %= money10

print('-' * 30)
print('50,000 {}장'.format(money50000Cnt))
print('10,000 {}장'.format(money10000Cnt))
print('5,000 {}장'.format(money5000Cnt))
print('1,000 {}장'.format(money1000Cnt))
print('500 {}개'.format(money500Cnt))
print('100 {}개'.format(money100Cnt))
print('50 {}개'.format(money50Cnt))
print('10 {}개'.format(money10Cnt))
print('-' * 30)
상품 가격 입력: 177777
지불 금액: 200000
거스름 돈: 22220(원단위 절사)
------------------------------
50,000 0장
10,000 2장
5,000 0장
1,000 2장
500 0개
100 2개
50 0개
10 2개
------------------------------

국수영 점수 입력 후 최고/최저 점수 과목과 점수차를 각각 출력해보자.

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

totalScore = korScore + engScore + matScore
avgScore = totalScore / 3

maxScore = korScore
maxSubject = '국어'
if engScore > maxScore:
    maxScore = engScore
    maxSubject = '영어'

if matScore > maxScore:
    maxScore = matScore
    maxSubject = '수학'

minScore = korScore
minSubject = '국어'
if engScore < minScore:
    minScore = engScore
    minSubject = '영어'

if matScore < minScore:
    minScore = matScore
    minSubject = '수학'

gap = maxScore - minScore

print('총점: {}'.format(totalScore))
print('평균: %.2f' % avgScore)
print('-' * 30)
print('최고 점수 과목(점수): {}({})'.format(maxSubject, maxScore))
print('최저 점수 과목(점수): {}({})'.format(minSubject, minScore))
print('최고, 최저 점수 차이: {}'.format(gap))
print('-' * 30)
#국어 100점, 영어 90점,수학 80점인 경우

총점: 270
평균: 90.0
------------------------------
최고 점수 과목(점수): 국어(100)
최저 점수 과목(점수): 수학(80)
최고, 최저 점수 차이: 20
------------------------------

시, 분, 초를 입력하면 초로 환산하는 프로그램을 만들어보자.

hou = int(input('시간 입력: '))
min = int(input('분 입력: '))
sec = int(input('초 입력: '))

print('{}초'.format(format(hou * 60 * 60 + min * 60 + sec, ',')))
시간 입력: 1
분 입력: 30
초 입력: 10
5,410초

복리계산기 프로그램을 만들어보자.

money = int(input('금액 입력: '))
rate = float(input('이율 입력: '))
term = int(input('기간 입력: '))

targetMoney = money

for i in range(term):
    targetMoney += targetMoney * rate * 0.01

targetMoneyFormat = format(int(targetMoney), ',')

print('-' * 30)
print('원금: {}'.format(format(money, ',')))
print('이율: {}'.format(rate))
print('{}년 후 금액: {}원'.format(term, targetMoneyFormat))
print('-' * 30)
이율 입력: 3
기간 입력: 2
------------------------------
원금: 50,000,000
이율: 3.0
2년 후 금액: 53,045,000원
------------------------------

고도를 입력하면 기온이 출력되는 프로그램을 만들어보자.

(고도가 60m 올라갈 때마다 기온이 0.8도 내려감, 지면온도는 29도)

#고도가 60~119m일때는 -0.8도, 120m일때는 -1.6도로 계산됨.
baseTemp = 29
step = 60
stepTemp = 0.8

height = int(input('고도 입력: '))

targetTemp = baseTemp - (height // step * 0.8)

print('지면 온도: {}'.format(baseTemp))
print('고도 %d의 기온: %.2f도 ' % (height, targetTemp))
고도 입력: 61
지면 온도: 29
고도 61의 기온: 28.20도 
#고도가 1~60m일때는 -0.8도, 61~120m일때는 -1.6도로 계산됨.
baseTemp = 29
step = 60
stepTemp = 0.8

height = int(input('고도 입력: '))

targetTemp = baseTemp - (height // step * 0.8)

if height % step != 0:
    targetTemp -= stepTemp

print('지면 온도: {}'.format(baseTemp))
print('고도 %d의 기온: %.2f도 ' % (height, targetTemp))
고도 입력: 61
지면 온도: 29
고도 61의 기온: 27.40도 

빵과 우유를 학생들에게 동일하게 나눠주고 남은 갯수를 구해보자.

bread = 197
milk = 152
student = 17

print('학생 한명이 받는 빵 개수 : {}'.format(bread // student))
print('학생 한명이 받는 우유 개수 : {}'.format(milk // student))

print('남은 빵 개수: {}'.format(bread % student))
print('남은 우유 개수: {}'.format(milk % student))
학생 한명이 받는 빵 개수 : 11
학생 한명이 받는 우유 개수 : 8
남은 빵 개수: 10
남은 우유 개수: 16

백신 접종 대상자를 구분하기 위한 프로그램을 만들어보자.

(19세 이하 또는 65세 이상이면 출생 연도 끝자리에 따른 접종
그렇지 않으면 하반기 일정 확인)

age = int(input('나의 입력: '))

if age <= 19 or age >= 65:
    endNum = int(input('출생년도 끝자리 입력: '))
    if endNum == 1 or endNum == 6:
        print('월요일 접종 가능!!')
    elif endNum == 2 or endNum == 7:
        print('화요일 접종 가능!!')
    elif endNum == 3 or endNum == 8:
        print('수요일 접종 가능!!')
    elif endNum == 4 or endNum == 9:
        print('목요일 접종 가능!!')
    elif endNum == 5 or endNum == 0:
        print('금요일 접종 가능!!')

else:
    print('하반기 일정 확인하세요.')
나의 입력: 74
출생년도 끝자리 입력: 9
목요일 접종 가능!!
나의 입력: 24
하반기 일정 확인하세요.

길이(cm)를 입력하면 inch로 환산하는 프로그램을 만들어보자.

byInch = 0.39
lengthMM = int(input('길이(cm) 입력: '))
lenghtInch = lengthMM * byInch

print('{}mm -> {}inch'.format(lengthMM, lenghtInch))byInch = 0.39
lengthMM = int(input('길이(cm) 입력: '))
lenghtInch = lengthMM * byInch

print('{}cm -> {}inch'.format(lengthMM, lenghtInch))
길이(cm) 입력: 68
68cm -> 26.52inch

조건문

교통 과속 위반 프로그램을 만들어보자. (제한속도: 50km)

carSpeed = int(input('속도 입력: '))
limitSpeed = 50

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

문자 메시지 길이에 따라 요금이 결정되는 프로그램을 만들어보자.

문자 길이 50이하 -> SMS발송(50원 부과)
문자 길이 50초과 -> MMS발송(100원 부과)

message = input('메시지 입력: ')
lenMessage = len(message)

if lenMessage <= 50:
    msPrice = 50
    print('SMS 발송')

if lenMessage > 50:
    msPrice = 100
    print('MMS 발송')

print('메시지 길이: {}'.format(lenMessage))
print('메시지 발송 요금: {}'.format(msPrice))
메시지 입력: 안녕
SMS 발송
메시지 길이: 2
메시지 발송 요금: 50
메시지 입력: 안녕하세요. 오늘은 날씨가 정말 추운 12월 7일 수요일입니다. 벌써 올해가 다 지나가네요.
MMS 발송
메시지 길이: 51
메시지 발송 요금: 100

총점, 평균, 편차를 출력하는 프로그램을 만들어보자.

  • 과목별 점수를 입력하면 총점, 평균, 편차를 출력한다.
  • 평균은 다음과 같다.
    (국어: 85, 영어:82, 수학:89, 과학: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))
국어 점수: 98
영어 점수: 100
수학 점수: 93
과학 점수: 97
국사 점수: 95
----------------------------------------------------------------------
총점: 483(58), 평균: 96(11)
국어: 98(13), 영어: 100(18), 수학: 93(4), 과학: 97(22), 국사: 95(1)
----------------------------------------------------------------------
국어 편차: +++++++++++++(13)
영어 편차: ++++++++++++++++++(18)
수학 편차: ++++(4)
과학 편차: ++++++++++++++++++++++(22)
국사 편차: +(1)
총점 편차: ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++(58)
평균 편차: +++++++++++(11)

난수를 이용해서 홀/짝 게임을 만들어보자.

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('오답! 짝수입니다.')
# 1(홀) 선택
홀/짝 선택: 1.홀 	 2.짝
정답! 홀수입니다.

홀/짝 선택: 1.홀 	 2.짝
오답! 짝수입니다.

난수를 이용해서 가위, 바위, 보 게임을 만들어보자.

import random

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))
# 3(보) 선택
가위,바위,보 선택: 1.가위 	 2.바위 	 3.보
무승부
컴퓨터: 3, 유저: 3

가위,바위,보 선택: 1.가위 	 2.바위 	 3.보
컴퓨터: 패, 유저: 승
컴퓨터: 2, 유저: 3

요금표를 참고해서 상수도 요금 계산기를 만들어보자.

가정용: 540원
대중탕용: 50이하 820원, 50초과 300이하 1920원, 300초과 2400원
공업용: 500이하 240원, 500초과 470원

part = int(input('업종 선택 (1. 가정용 2. 대중탕용 3.공업용) :'))
useWater = int(input('사용량 입력'))
unitPrice = 0

if part == 1:
    unitPrice = 540

elif part == 2:
    if useWater <= 50:
        unitPrice = 820
    elif useWater > 50:
        unitPrice = 1920
    elif useWater > 300:
        unitPrice = 2400

elif part == 3:
    if useWater <= 500:
        unitPrice = 240
    else:
        unitPrice = 470

print('=' * 30)
print('상수도 요금표')
print('-' * 30)
print('사용량 \t: \t요금')
userPrice = useWater * unitPrice
print('{} \t: \t{}원'.format(useWater, userPrice))
print('=' * 30)
사용량 입력700
==============================
상수도 요금표
------------------------------
사용량 	: 	요금
700 	: 	329000원
==============================

PC에서 난수를 발생하면 사용자가 맞추는 게임을 만들어보자.

tryCount = 0
gameFlag = True

while gameFlag:
    tryCount += 1
    pNum = int(input('1에서 1,000까지의 정수 입력: '))

    if rNum == pNum:
        print('정답')
        gameFlag = False

    else:
        if rNum > pNum:
            print('UP')

        else:
            print('DOWN')

print('난수: {}, 시도 횟수: {}'.format(rNum, tryCount))
1에서 1,000까지의 정수 입력: 500
UP
1에서 1,000까지의 정수 입력: 700
UP
1에서 1,000까지의 정수 입력: 800
DOWN
1에서 1,000까지의 정수 입력: 777
DOWN
1에서 1,000까지의 정수 입력: 750
DOWN
1에서 1,000까지의 정수 입력: 730
UP
1에서 1,000까지의 정수 입력: 740
UP
1에서 1,000까지의 정수 입력: 745
DOWN
1에서 1,000까지의 정수 입력: 742
UP
1에서 1,000까지의 정수 입력: 743
정답
난수: 743, 시도 횟수: 10

실내온도를 입력하면 스마트에어컨 상태가 자동으로 설정되는 프로그램을 만들어보자.

18도 이하: off
18도 초과 24도 이하: 약
24도 초과 26도 이하: 중
26도 초과: 강

innerTemp = int(input('실내온도 입력: '))

if innerTemp <= 18:
    print('에어컨 끔')

elif innerTemp > 18 and innerTemp <= 24:
    print('에어컨 약')


elif innerTemp > 24 and innerTemp <= 26:
    print('에어컨 중')

elif innerTemp > 26:
    print('에어컨 강')
실내온도 입력: 25
에어컨 중

반복문

1부터 20까지 정수 중 십의 자리와 일의 자리에 대해 각각 홀/짝수를 구분하는 프로그램을 만들어보자.

for i in range(1, 21):
    if i <= 9:
        if i % 2 == 0:
            print('[{}]: 짝수'.format(i))
        else:
            print('[{}]: 홀수'.format(i))

    else:
        num10 = i // 10
        num1 = i % 10

        result10 = ''
        if num10 % 2 == 0:
            result10 = '짝수'
        else:
            result10 = '홀수'

        result1 = '0'
        if num1 != 0:
            if num1 % 2 == 0:
                result1 = '짝수'
            else:
                result1 = '홀수'

        print('[{}] 십의자리: {}, 일의자리: {}'.format(i, result10, result1))
[1]: 홀수
[2]: 짝수
[3]: 홀수
[4]: 짝수
[5]: 홀수
[6]: 짝수
[7]: 홀수
[8]: 짝수
[9]: 홀수
[10] 십의자리: 홀수, 일의자리: 0
[11] 십의자리: 홀수, 일의자리: 홀수
[12] 십의자리: 홀수, 일의자리: 짝수
[13] 십의자리: 홀수, 일의자리: 홀수
[14] 십의자리: 홀수, 일의자리: 짝수
[15] 십의자리: 홀수, 일의자리: 홀수
[16] 십의자리: 홀수, 일의자리: 짝수
[17] 십의자리: 홀수, 일의자리: 홀수
[18] 십의자리: 홀수, 일의자리: 짝수
[19] 십의자리: 홀수, 일의자리: 홀수
[20] 십의자리: 짝수, 일의자리: 0

반복문 2~ 4복습, 5~6 다시공부

profile
데이터 입문자

0개의 댓글