02-02. 파이썬 기초 문제풀이
데이터와 변수
name = '홍길동'
product = '야구글러브'
orderNo= 2568956
payMethod = '신용카드'
productPrice = 110000
payPrice = 100000
usePoint = 10000
payDate = '2021/08/03 21:50:12'
payDiv = 6
payDivCategory = '무'
phone = '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: ', payDiv)
print('할부유형\t: ', payDivCategory)
print('문의\t: ', phone)
print('-'*50)
print('저희 사이트를 이용해 주셔서 감사합니다.')

userMsg = input('메세지 입력: ')
print('메세지 길이: {}'.format(len(userMsg)))

'''
파이썬[3](영어: Python)은 1991년[4] 프로그래머인 귀도 반 로섬[5]이 발표한 고급 프로그래밍 언어로,
플랫폼에 독립적이며 인터프리터식, 객체지향적, 동적 타이핑(dynamically typed) 대화형 언어이다.
파이썬이라는 이름은 귀도가 좋아하는 코미디 〈Monty Python's Flying Circus〉에서 따온 것이다.
'''
article = "파이썬[3](영어: Python)은 1991년[4] 프로그래머인 귀도 반 로섬[5]이 발표한 고급 프로그래밍 언어로, \
플랫폼에 독립적이며 인터프리터식, 객체지향적, 동적 타이핑(dynamically typed) 대화형 언어이다. \
파이썬이라는 이름은 귀도가 좋아하는 코미디 〈Monty Python's Flying Circus〉에서 따온 것이다."
strIdx = article.find('객체지향적')
print("'객체지향' 문자열 위치: {}".format(strIdx))

width = float(input('가로 길이 입력: '))
height = float(input('세로 길이 입력: '))
triangleArea = width * height / 2
squareArea = width * height
print('-'*25)
print('삼각형 넓이 : %.2f' % triangleArea)
print('사각형 넓이 : %.2f' % squareArea)
print('-'*25)

pi = 3.14
radius = float(input('반지름(cm) 입력: '))
circleArea = pi * radius * radius
circleLength = 2 * pi * radius
print('원의 넓이\t: %d' % circleArea)
print('원의 둘레길이\t: %d' % circleLength)
print('원의 넓이\t: %.1f' % circleArea)
print('원의 둘레길이\t: %.1f' % circleLength)
print('원의 넓이\t: %.3f' % circleArea)
print('원의 둘레길이\t: %.3f' % circleLength)

name = input('이름 입력: ')
mail = input('메일 입력: ')
account_id = input('아이디 입력: ')
pw = input('비밀번호 입력: ')
ss_num1 = input('주민번호 앞자리 입력: ')
ss_num2 = input('주민번호 뒷자리 입력: ')
address = input('주소 입력: ')
print('-'*30)
print(f'이름\t: {name}')
print(f'메일\t: {mail}')
print(f'아이디\t: {account_id}')
pw_hidden = '*' * len(pw)
print(f'비밀번호\t: {pw_hidden}')
ss_num_hidden = ss_num2[0] + ('*'*6)
print(f'주민번호 : {ss_num1} - {ss_num_hidden}')
print(f'메일 : {address}')
print('-'*30)

w = input('체중 입력(kg): ')
h = input('신장 입력(cm): ')
if w.isdigit():
w = int(w)
if h.isdigit():
h = int(h) / 100
print('체중 : {}kg'.format(w))
print('신장 : {}m'.format(h))
bmi = w / (h * h)
print('BMI : %f' % bmi)

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

score1 = input('중간고사 점수: ')
score2 = input('기말고사 점수: ')
if score1.isdigit() and score2.isdigit():
score1 = int(score1)
socre2 = int(score2)
total_score = score1 + socre2
avg_score = total_score / 2
print('총점: {}, 평균: {}'.format(total_score, avg_score))
else:
print('점수 잘못 입력 됨')

select_num = input('언어 선택(Choose your language): 1. 한국어\t2. English')
if int(select_num) == 1:
menu = '1 샌드위치 \t 2. 햄버거 \t 3. 쥬스 \t 4. 커피 \t 5. 아이스크림'
elif int(select_num) == 2:
menu = '1 Sandwich \t 2. Burger \t 3. Juice \t 4. Coffee \t 5. Icecream'
print(menu)

import datetime
today = datetime.datetime.today()
myAge = input('나이 입력: ')
if myAge.isdigit():
years_left = 100 - int(myAge)
date_of_100 = today.year + years_left
print('{}년 -- {}년 후에 100살!'.format(date_of_100, years_left))
else:
print('나이를 잘못 입력하였습니다.')

연산자
money50000 = 50000; money10000 = 10000; money5000 = 5000; money1000 = 1000; money500 = 500; money100 = 100; money10 = 10
money50000Cnt = 0; money10000Cnt = 0; money5000Cnt = 0; money1000Cnt = 0; money500Cnt = 0; money100Cnt = 0; money10Cnt = 0
productPrice = int(input('상품 가격 입력: '))
payPrice = int(input('지불 금액: '))
if payPrice > productPrice :
changeMoney = payPrice - productPrice
changeMoney = (changeMoney // 10) * 10
print('거스름돈: ', changeMoney)
if changeMoney > money50000:
money50000Cnt = 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 > money10:
money10Cnt = changeMoney // money10
changeMoney %= money10
print('-'*30)
print('5만원 {}장'.format(money50000Cnt))
print('1만원 {}장'.format(money10000Cnt))
print('5천원 {}장'.format(money5000Cnt))
print('1천원 {}장'.format(money1000Cnt))
print('500원 {}장'.format(money500Cnt))
print('100원 {}장'.format(money100Cnt))
print('10원 {}장'.format(money10Cnt))
print('-'*30)

korScore = int(input('국어 점수 입력: '))
engScore = int(input('영어 점수 입력: '))
mathScore = int(input('수학 점수 입력: '))
totalScore = korScore + engScore + mathScore
avgScore = totalScore / 3
maxScore = korScore
maxSubject = '국어'
if engScore > maxScore:
maxScore = engScore
maxSubejct = '영어'
if mathScore > maxScore:
maxScore = mathScore
maxSubject = '수학'
minScore = korScore
minSubject = '국어'
if engScore < minScore:
minScore = engScore
minSubject = '영어'
if mathScore < minScore:
minScore = mathScore
minSubject = '수학'
difScore = maxScore - minScore
print('총점: {}'.format(totalScore))
print('평균: %.2f' % avgScore)
print('*'*30)
print('최고점수 과목(점수): {}({})'.format(maxScore, maxSubject))
print('최저점수 과목(점수): {}({})'.format(minScore, minSubject))
print('최고-최저 차이: {}'.format(difScore))
print('*'*30)

hou = int(input('시간 입력: '))
min = int(input('분 입력: '))
sec = int(input('초 입력: '))
total_sec = hou * 60 * 60 + min * 60 + sec
print('{}초'.format(format(total_sec, ',')))

money = int(input('금액 입력: '))
rate = float(input('이율 입력: '))
term = int(input('기간 입력: '))
targetMoney = money
for i in range(term):
targetMoney += (targetMoney * rate * 0.01)
targetMoneyFormatted = format(int(targetMoney), ',')
print('-'*30)
print('이율: {}'.format(rate))
print('원금: {}'.format(format(money, ',')))
print('{}년 후 금액: {}원'.format(term, targetMoneyFormatted))
print('-'*30)

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('고도 %dm의 기온: %.2f' % (height, targetTemp))

bread = 197
milk = 152
student_cnt = 17
print('학생 한명이 갖게되는 빵 개수: {}'.format(bread // student_cnt))
print('학생 한명이 갖게되는 우유 개수: {}'.format(milk // student_cnt))
print('남는 빵 개수: {}'.format(bread % student_cnt))
print('남는 우유 개수: {}'.format(milk % student_cnt))

'''
"19세 이상 또는 65세 이하이면 출생 연도 끝자리에 따른 접종, 그렇지 않으면 하반기 일정 확인"
'''
inputAge = int(input('나이 입력:'))
if inputAge >= 29 or inputAge <= 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('하반기 일정 확인')

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

조건문
carSpeed = int(input('속도 입력: '))
limitSpeed = 50
if carSpeed > 50:
print('안전속도 위반! 과태료 5만원 부과 대상.')
else:
print('안전속도 준수!')

'''
- 문자 길이 50이하 --> SMS발송(50원 부과)
- 문자 길이 50초과 --> MMS발송(100원 부과)
'''
message = input('메시지 입력: ')
lenMessage = len(message)
msgPrice = 50
if lenMessage <= 50:
msgPrice = 50
print('SMS발송')
if lenMessage > 50:
msgPrice = 100
print('MMS발송')
print('메시지 길이: {}'.format(lenMessage))
print('메시지 발송 요금: {}'.format(msgPrice))

'''
과목별 점수를 입력하면 총점, 평균, 편차를 출력한다.
평균은 다음과 같아: 국어 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('-'*30)
print('총점: {}({}), 평균: {}({})'.format(totalScore, totalGap, avgScore, avgGap))
print('국어: {}({}), 영어: {}({}), 수학: {}({}), 과학: {}({}), 국사: {}({})'.format(
korScore, korGap, engScore, engGap, matScore, matGap, sciScore, sciGap, hisScore, hisGap))
print('-'*30)
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))

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('실패! 짝수!')

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))

'''
업종별 - 가정용 | 대중탕용 | 공업용
사용량 - | 50이하, 50초과 300이하, 300초과 | 500이하, 500초과
단가(원) - 540 | 820원, 1,920원, 2,400원 | 240원, 470원
'''
part = int(input('업종 선택(1.가정용 | 2.대중탕용 | 3.공업용): '))
useWater = int(input('사용량 입력: '))
unitPrice = 0
if part == 1:
unitPrice = 540
pass
elif part ==2:
if useWater <= 50:
unitPrice = 820
elif useWater > 50 and useWater <= 300:
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 요금')
usePrice = useWater * unitPrice
print('{} \t : \t {}원'.format(useWater, format(usePrice, ',')))
print('='*30)

'''
- 미세먼지 측정 수치가 150 이하면 차량 5부제 실시
- 미세먼지 측정 수치가 150을 초과하면 차량 2부제 실시
- 차량 2부제를 실시하더라도 영업용차량은 5부제 실시
- 미세먼지 수치, 차량 종류, 차량 번호를 입력하면 운행 가능 여부 출력
'''
import datetime
today = datetime.datetime.today()
day = today.day
limitDust = 150
dustNum = int(input('미세먼지 수치 입력: '))
carType = int(input('차량 종류 선택: 1.승용차 \t 2.영업용차'))
carNumber = int(input('차량 번호 입력: '))
print('-'*30)
print(today)
print('-'*30)
if dustNum > limitDust and carType == 1:
if (day % 2) == (carNumber % 2):
print('차량 2부제 적용')
print('차량 2부제로 금일 운행제한 대상 차량입니다.')
else:
print('금일 운행 가능합니다.')
if dustNum > limitDust and carType == 2:
if (day % 5) == (carNumber % 5):
print('차량 5부제 적용')
print('차량 5부제로 금일 운행제한 대상 차량입니다.')
else:
print('금일 운행 가능합니다.')
if dustNum <= limitDust:
if (day % 5) == (carNumber % 5):
print('차량 5부제 적용')
print('차량 5부제로 금일 운행제한 대상 차량입니다.')
else:
print('금일 운행 가능합니다.')
print('-'*30)

'''
- PC가 난수(1~1000)를 발생하면 사용자가 숫자(정수)를 입력한다.
- 사용자가 난수를 맞추면 게임이 종료된다.
- 만약, 못 맞추게 되면 난수와 사용자 숫자의 크고 작음을 출력한 후 사용자한테 다시 기회를 준다.
- 최종적으로 사용자가 시도한 횟수를 출력한다.
'''
import random
rNum = random.randint(1, 1000)
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('난수가 크다!')
else:
print('난수가 작다!')
print('난수: {}, 시도 횟수: {}'.format(rNum, tryCount))

'''
실내온도(에어컨 상태)
18도 이하(off) | 18도 초과 22도 이하(매우 약) | 22도 초과 24도 이하(약) | 24도 초과 26도 이하(중) | 26도 초과 28도 이하(강) | 28도 초과(매우 강)
'''
innerTemp = int(input('실내온도 입력:'))
if innerTemp <= 18:
print('에어컨 off')
elif innerTemp > 18 and innerTemp <= 22:
print('매우 약')
elif innerTemp > 22 and innerTemp <= 24:
print('약')
elif innerTemp > 24 and innerTemp <= 26:
print('중')
elif innerTemp > 26 and innerTemp <= 28:
print('강')
elif innerTemp > 28:
print('매우 강')

반복문
for i in range(1, 101):
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))

fNum = int(input('정수 입력: '))
addSum = 0
for i in range(1, (fNum+1)):
addSum += i
addSumFormatted = format(addSum, ',')
print('정수까지의 합 결과: {}'.format(addSumFormatted))
oddSum = 0
for i in range(1, (fNum+1)):
if i % 2 != 0:
oddSum += i
oddSumFormatted = format(oddSum, ',')
print('홀수 합 결과: {}'.format(oddSumFormatted))
evenSum = 0
for i in range(1, (fNum+1)):
if i % 2 == 0:
evenSum += i
evenSumFormatted = format(evenSum, ',')
print('짝수 합 결과: {}'.format(evenSumFormatted))
factorialResult = 1
for i in range(1, (fNum+1)):
factorialResult *= i
factorialResultFormatted = format(factorialResult, ',')
print('팩토리얼 결과: {}'.format(factorialResultFormatted))

for i in range(1,6):
for j in range(i):
print('*', end='')
print()

for i1 in range(1, 6):
for i2 in range(6-i1-1):
print(' ', end='')
for i3 in range(i1):
print('*', end='')
print()

for i in range(5, 0, -1):
for j in range(i):
print('*', end='')
print()

for i in range(5, 0, -1):
for j in range(5 - i):
print(' ', end='')
for j in range(i):
print('*', end='')
print()

for i in range(1, 10):
if i < 6:
for j in range(i):
print('*', end='')
else:
for j in range(10-i):
print('*', end='')
print()

for i in range(1, 6):
for j in range(1, 6):
if j == i:
print('*', end='')
else:
print(' ', end='')
print()

'''
버스 A, B 운행 정보
- 오전 6시 첫차 : 오후 23시 운행 종료
- 버스A : 15분 간격 운행
- 버스B : 13분 간격 운행
버스 C 운행 정보
- 6시 20분 첫차 : 오후 22시 운행 종료
- 버스C : 8분 간격 운행
'''
busA = 15
busB = 13
busC = 8
totalMin = 60*17
for i in range(totalMin+1):
if i < 20 or i > (totalMin - 60):
if (i % busA == 0) and (i % busB == 0):
print('busA와 busB 동시 정차', end='')
hour = 6 + (i // 60)
min = i % 60
print('\t{}:{}'.format(hour, min))
else:
if i % busA == 0 and i % busB == 0:
print('busA와 busB 동시 정차', end='')
hour = 6 + (i // 60)
min = i % 60
print('\t{}:{}'.format(hour, min))
elif i % busA == 0 and i % busC == 0:
print('busA와 busC 동시 정차', end='')
hour = 6 + (i // 60)
min = i % 60
print('\t{}:{}'.format(hour, min))
elif i % busB == 0 and i % busC == 0:
print('busB와 busC 동시 정차', end='')
hour = 6 + (i // 60)
min = i % 60
print('\t{}:{}'.format(hour, min))

gearATCnt = int(input('GearA 톱니수 입력: '))
gearBTCnt = int(input('GearB 톱니수 입력: '))
gearA = 0
gearB = 0
leastNum = 0
flag = True
while flag:
if gearA != 0:
if gearA != leastNum:
gearA += gearATCnt
else:
flag = False
else:
gearA += gearATCnt
if gearB != 0 and gearB % gearATCnt == 0:
leastNum = gearB
else:
gearB += gearBTCnt
print('최초 만나는 톱니수(최소공배수): {}톱니'.format(leastNum))
print('gearA 회전수: {}회전'.format(int(leastNum / gearATCnt)))
print('gearB 회전수: {}회전'.format(int(leastNum / gearBTCnt)))

'''
윤년 조건 (윤년: 4년마다 돌아오되, 아래 조건)
- 연도가 4로 나누어떨어지고 100으로 나누어떨어지지 않으면 윤년이다.
- 또는 연도가 400으로 나누어떨어지면 윤년이다.
'''
year = int(input('연도 입력:'))
if (year % 4 == 0 and year & 100 != 0) or (year % 400 == 0):
print('{}년: 윤년'.format(year))
else:
print('{}년: 평년'.format(year))

for year in range(2021, (2021+101)):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print('{}년: 윤년'.format(year))
else:
print('{}년: 평년'.format(year))
