파이썬 언어를 만든 사람
귀도 반 로섬
파이썬의 특징
문법 구조가 쉬워 비전공자도 쉽게 배울 수 있다
이미 잘 만들어져 있는 모듈이 많아 사용이 편리하다
무한 정수를 처리할 수 있다
온라인상에 커뮤니티가 잘 형성되어 있어 많은 정보를 얻을 수 있다
JetBrains에서 만들었다
python을 설치후에 PyCharm을 설치해야함
변경되는 정보만 변수로 지정
name = '홍길동' product = '야구글러브' orderNo = 2568956 payMethod = '신용카드' productPrice = 110000 payPrice = 100000 usePoint = 100000 payDate = '2021/08/03 21:50:12' payDiv = 6 payDivCategory = '무' phone = '02-1234-5678'
print(name, '고객님 안녕하세요') print(name, '고객님의 주문이 완료되었습니다') print(name, '다음은 주문건에 대한 상세 내역입니다') print('-' * 50) print('상품명 : ', product) print('주문번호 : ', orderNo) print('결제방법 : ', payMethod) print('상품금액 : ', productPrice) print('경제금액 : ', payPrice) print('포인트 : ', usePoint) print('결제일시 : ', payDate) print('할부 : ', payDiv) print('할부유형 : ', payDivCategory) print('문의 : ', phone) print('-' * 50) print('저희 사이트를 이용해 주셔서 감사합니다')
소수점 아래 %f 사용
width = float(input('가로 길이 입력 : ')) height = float(input('세로 길이 입력 : ')) resultTri = width * height / 2 resultSqu = width * height
print('-' * 25) print('삼각형 넓이 : %f' % resultTri) print('사각형 넓이 : %f' % resultSqu) print('삼각형 넓이 : %.2f' % resultTri) print('사각형 넓이 : %.2f' % resultSqu) print('-' * 25)
정수는 %d 실수는 %f
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)
isdigit(): 숫자인지 확인 (숫자면 True, 아니면 False)
# BMI = 몸무게(kg) / (신장(m) * 신장(m)) weight = input('체중 입력(g): ') height = input('신장 입력(cm): ')
if weight.isdigit(): weight = int(weight) / 10 if height.isdigit(): height = int(height) / 100
print('체중 : {}kg' .format(weight)) print('신장 : {}m' .format(height)) bmi = weight / (height * height) print('BMI : %f' % bmi)
temp에 넣은후에 값을 교환
num1 = 10 num2 = 20 print('num1: {}, num2: {}' .format(num1, num2))
tempNum = num1 num1 = num2 num2 = tempNum print('num1: {}, num2: {}' .format(num1, num2))
isdigit(): 숫자인지 확인 (숫자면 True, 아니면 False)
midTest = input('중간 고사 점수: ') lasTest = input('기말 고사 점수: ')
if midTest.isdigit() and lasTest.isdigit(): midTest = int(midTest) lasTest = int(lasTest) total = midTest + lasTest average = total / 2 print('총점: {}, 평균: {}' .format(total, average)) else: print('잘 못 입력했습니다')
selectNum = input('언어 선택(Choose your language): 1.한국어 \t 2.English')
if selectNum == '1': menu = '1.샌드위치 \t 2.햄버거 \t 3.쥬스 \t 4.커피 \t 5.아이스크림' elif selectNum == '2': menu = '1.Sandwich \t 2.Hamburger \t 3.Juice \t 4.Coffee \t 5.Ice cream' print(menu)
날짜 및 시간 정보는 datetime 모듈사용
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('잘 못 입력했습니다')
1원단위 절사를 위해서 changeMoney = (changeMoney // 10) * 10 사용
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('거스름 돈 : {}(원단위 절사)' .format(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('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('10 {}장' .format(money10cnt)) print('-' * 30)
먼저 한 과목을 maxScore나 minScore에 넣은 후 비교하여 크거나 작으면 값에 대입
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 = '수학'
difScore = maxScore - minScore print('총점: {}' .format(totalScore)) print('평균: %.2f' % avgScore) print('-' * 30) print('최고 점수 과목(점수): {}({})' .format(maxSubject, maxScore)) print('최저 점수 과목(점수): {}({})' .format(minSubject, minScore)) print('최고, 최저 점수 차이: {}' .format(difScore)) print('-' * 30)
format 함수를 이용하면 문자로 변함
hou = int(input('시간 입력: ')) min = int(input('분 입력: ')) sec = int(input('초 입력: ')) print('{}초'.format(format(hou * 60 * 60 + min * 60 + sec, ',')))
이율을 곱할때는 이율에 0.01도 같이 곱해줘야한다
money = int(input('금액 입력: ')) rate = float(input('이율 입력: ')) term = int(input('기간 입력: ')) targetMoney = money
for i in range(term): targetMoney += (targetMoney * rate * 0.01)
targetMoneyFormated = format(int(targetMoney), ',') print('-' * 30) print('이율: {}' .format(rate)) print('원금: {}' .format(format(money, ','))) print('{}년 후 금액: {}원' .format(term, targetMoneyFormated)) print('-' * 30)
height가 step으로 나누어 떨어지지 않으면 targetTemp에서 stepTemp를 한번 더 빼준다
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 = 17
print('학생 한 명이 갖게 되는 빵 개수 : {}' .format(bread // student)) print('학생 한 명이 갖게 되는 우유 개수 : {}' .format(milk // student)) print('남는 빵 개수 : {}' .format(bread % student)) print('남는 우유 개수 : {}' .format(milk % student))
inputAge = int(input('나이 입력: '))
if inputAge <= 19 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('하반기 일정 확인하세요')
(1mm = 0.039inch)
byInch = 0.039 lengthMM = int(input('길이(mm) 입력: ')) lengthInch = lengthMM * byInch
print('{}mm -> {}inch' .format(lengthMM, lengthInch))
speed = int(input('속도 입력: '))
if speed <= 50: print('안전속도 준수!!') else: print('안전속도 위반!! 과태로 50,000원 부과 대상!!!')
text = input('메시지 입력: ') textLength = len(text) textPrice = 50
if textLength <= 50: textPrice = 50 print('SMS 발송!!') if textLength > 50: textPrice = 100 print('MMS 발송!!')
print('메시지 길이 {}' .format(textLength)) print('메시지 발송 요금 {}' .format(textPrice))
- 값은 abs를 사용하여 절댓값을 만들어준다
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)
random.randint(1, 2) -> 컴퓨터가 1과 2중 랜덤으로 고름
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('실패!! 짝수!!!')
이기는 경우 3개를 제외하고 무승부나 패배
import random comNum = random.randint(1, 3) userNum = int(input('가위, 바위, 보 선택: 1.가위 \t 2.바위 \t 3.보 '))
if (comNum == 1 and userNum == 2) or \ (comNum == 2 and userNum == 3) or \ (comNum == 3 and userNum == 1): print('컴퓨터: 패, 유저: 승') elif comNum == userNum: print('무승부') else: print('컴퓨터: 승, 유저: 패')
print('컴퓨터: {}, 유저: {}' .format(comNum, userNum))
part = int(input('업종 선택(1.가정용 \t 2.대중탕용 \t 3.공업용) : ')) useWater = int(input('사용량 입력: ')) unitPrice = 0
if part == 1: unitPrice = 540
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 요금') userPrice = useWater * unitPrice print('{} \t : \t {}원' .format(useWater, format(userPrice, ','))) print('=' * 30)
2부제 5부제는 번호판 끝자리 기준
% 2, % 5 를 통해 구분
import datetime today = datetime.datetime.today() day = today.day
limitDust = 150 dustNum = int(input('미세먼지 수치 입력: ')) carType = int(input('차량 종류 선택: 1.승용차 \t 2.영업용차')) carNum = int(input('차량 번호 입력: ')) print('-' * 30) print(today) print('-' * 30)
- 승용차 미세먼지 측정 수치 제한 초과
if dustNum >= limitDust and carType == 1: if (day % 2) == (carNum % 2): print('차량 2부제 적용') print('차량 2부제로 금일 운행제한 대상 차량입니다') else: print('금일 운행 가능합니다')
- 영업용차 미세먼지 측정 수치 제한 초과
if dustNum >= limitDust and carType == 2: if (day % 5) == (carNum % 5): print('차량 5부제 적용') print('차량 5부제로 금일 운행제한 대상 차량입니다') else: print('금일 운행 가능합니다')
- 미세먼지 측정 수치 제한 이하
if dustNum <= limitDust: if (day % 5) == (carNum % 5): print('차량 5부제 적용') print('차량 5부제로 금일 운행제한 대상 차량입니다') else: print('금일 운행 가능합니다') print('-' * 30)
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))
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('에어컨: 매우 강')
문제풀이를 통해 복습하고 개념을 더 견고히하는 느낌이라 성취감이 들었다
문제를 보고 이렇게 구조를 짜면 되겠다 라는 생각이 한번에 안들때도 있었다
문제풀이는 역시 한번해서 실력이 느는것이 아니라는것을 느꼈다 자주 보고 풀어봐야겠다
주말에는 지금까지 한 내용을 바탕으로 문제를 복습해 보아야겠다