num1 = 20
fNum1 = 3.14
result = num1 * fNum1
print('result = {}'.format(result))
print('result = %.2f' % result)
str1 = 'Hi '
result = str1 * 7
print('result = {}'.format(result))
num1 = 0
num2 = 3
result = num1 / num2
print('result = {}'.format(result))
num1 = 0
num2 = 3
result = num2 / num1
print('result = {}'.format(result))
num1 = 10
num2 = 3
result = num1 % num2
print('num1 : {}, num2 : {}, result : {}'.format(num1, num2, result))
result = num1 // num2
print('num1 : {}, num2 : {}, result : {}'.format(num1, num2, result))
result = divmod(num1, num2)
print('result: {}'.format(result))
print('몫: {}, 나머지: {}'.format(result[0], result[1]))
* 첫 번째 인덱스([0])의 값이 몫, 두 번째 인덱스([1])의 값이 나머지이다.
n ** m
num1 = 2
num2 = 3
result = num1 ** num2
print('num1 : {}'.format(num1))
print('num2 : {}'.format(num2))
print('result : {}'.format(result))
import 명령어를 통해 모듈을 불러온다.
공식 : math.pow(n, m)
== n ** m
import math
print('2의 3제곱 %.2f' % math.pow(2, 3))
기본 공식은 거듭제곱의 것과 유사하다 : n ** (1/m)
result = 2 ** (1/2)
print('2의 제곱근 %f' % result)
print('2의 제곱근 %.2f' % result)
pow() 함수와 마친가지로 import 명령어를 통해 모듈을 불러온다.
제곱근과 pow() 함수의 관계와는 다르게 sqrt() 함수는 오직 데이터의 2 제곱근만 출력할 수 있다.
공식 : math.sqrt(n)
== n ** (1/2)
import math
print('2의 제곱근 %.2f' % math.sqrt(2))
아들이 엄마한테 용돈을 받는데, 첫 달에는 200원을 받고 매월 이전 달의 2배씩 인상하기로 했다. 12 개월째 되는 달에는 얼마를 받을 수 있는지 계산해 보자.
firstMonthMoney = 200
after12Month = ((firstMonthMoney * 0.01) ** 12) *100
print('12개월 후 용돈 : %.f원' % after12Month)
after12Month = int(after12Month)
strResult = format(after12Month, ',')
print('12개월 후 용돈 : %s원' % strResult)
firstMonthMoney = 200
after12Month = ((firstMonthMoney * 0.015) ** 11) * 200
print('12개월 후 용돈 : %.f원' % after12Month)
after12Month = int(after12Month)
strResult = format(after12Month, ',')
print('12개월 후 용돈 : %s원' % strResult)
예시)
num1 = 10
num1 = num1 + 5
num1 += 5
위 코드에서 2번째 코드가 할당 (대입) 연산자, 3번째가 복합 연산자의 예시이다.
결론적으로 복합 연산자는 산술 연산자에 ' = '를 붙인 것이라 봐도 무방하다.
숫자 비교를 위한 부등호와 동일하며, 연산 결과는 bool (True / False) 이다.
1. ' > ' (L이 R보다 크다)
2. ' >= ' (L이 R보다 크거나 같다)
3. ' < ' (L이 R보다 작다)
4. ' <= ' (L이 R보다 작거나 같다)
5. ' == ' (L과 R은 같은 값이다)
6. ' != ' (L과 R은 다른 값이다)
* 대문자 알파벳 < 소문자 알파벳
print('\'A\' -> {}'.format(ord('A')))
print('65 -> \'{}\''.format(chr(65)))
str1 = 'Hello'
str2 = 'hello'
print('{} == {} : {}'.format(str1, str2, (str1 == str2)))
print('{} != {} : {}'.format(str1, str2, (str1 != str2)))
피연산자의 논리 (True or False)를 이용한 연산
종류 : and, or, not
- and 연산자 (A and B) : A와 B 모두 True인 경우만 True 출력
- or 연산자 (A or B) : A와 B 중 어느 하나만 True이면 True 값 출력
- not 연산자 (not A) : A의 상태를 부정하는 결과 출력
print('not {} : {}'.format(True, (not True)))
print('not {} : {}'.format(False, (not False)))
korScore = int(input('국어 점수 : '))
engScore = int(input('영어 점수 : '))
mathScore = int(input('수학 점수 : '))
totalScore = (korScore + engScore + mathScore)
avgScore = (totalScore / 3)
print('평균 : {}, 결과 : {}'.format(avgScore, (avgScore > 70)))
print('국어 : {}, 결과 : {}'.format(korScore, (korScore > 60)))
print('영어 : {}, 결과 : {}'.format(engScore, (engScore > 60)))
print('수학 : {}, 결과 : {}'.format(mathScore, (mathScore > 60)))
print('과락 결과 : {}'.format(korScore and engScore and mathScore > 60))
print('과락 결과 : {}'.format(korScore and engScore and mathScore > 70))
passScore = 60
passAvgScore = 70
korScore = int(input('국어 점수 : '))
engScore = int(input('영어 점수 : '))
mathScore = int(input('수학 점수 : '))
scoreAvg = korScore + engScore + mathScore / 3
scoreAvgResult = scoreAvg >= passAvgScore
korResult = korScore >= passScore
engResult = engScore >= passScore
mathResult = mathScore >= passScore
subjectResult = korResult and engResult and mathResult
print('평균 : {}, 결과 : {}'.format(scoreAvg, scoreAvgResult))
print('국어 : {}, 결과 : {}'.format(korScore, korResult))
print('영어 : {}, 결과 : {}'.format(engScore, engResult))
print('수학 : {}, 결과 : {}'.format(mathScore, mathResult))
누군가 이미 만들어 놓은 훌륭한 기능 (Add-On 과 같은 것이라고 봐도 무방)
- 산술 연산자 관련 함수 :
<img src="https://velog.velcdn.com/images/juneleekorea/post/23118966-8115-4777-b99d-a75377a6a08e/image.png" width="30%" height="30%">
- 비교 연산자 관련 함수:
<img src="https://velog.velcdn.com/images/juneleekorea/post/2eabd231-10b8-426e-863c-024379ec1448/image.png" width="30%" height="30%">
- 논리 연산자 관련 함수:
<img src="https://velog.velcdn.com/images/juneleekorea/post/c7343bcf-3911-48b8-ae9b-c6ec7aa1546b/image.png" width="30%" height="30%">
국어, 영어, 수학 점수를 입력하면 조건식을 이용해서 과목별 결과와 전체 결과를 출력하는 코드를 작성해 보자.
과목별 합격 점수 : 60점 전체 합격 평균 점수 : 70
import operator
passScore = 60
passAvgScore = 70
korScore = int(input('국어 점수 : '))
engScore = int(input('영어 점수 : '))
mathScore = int(input('수학 점수 : '))
totalScore = korScore + engScore + mathScore
totalAvgScore = operator.truediv(totalScore, 3)
print('국어 : Pass' if operator.ge(korScore, passScore) else '국어 : Fail')
print('영어 : Pass' if operator.ge(engScore, passScore) else '영어 : Fail')
print('수학 : Pass' if operator.ge(mathScore, passScore) else '수학 : Fail')
print('시험 : Pass' if operator.ge(totalAvgScore, passScore) else '시험 : Fail')
print('총점 : %d, 평균 : %.2f' % (totalScore, totalAvgScore))
if 조건식:
실행문
userPoint = int(input('고객 포인트 입력 : '))
minAblePoint = 1000
print('포인트 사용 가능') if userPoint >= minAblePoint else \
print('포인트 사용 불가능')
result = '가능' if userPoint >= minAblePoint else '불가능'
print('포인트 사용 가능 여부 : {}'.format(result))
userPoint = int(input('고객 포인트 입력 : '))
minAblePoint = 1000
result = '가능' if userPoint >= minAblePoint else '불가능'
print('포인트 사용 가능 여부 : {}'.format(result))
userPoint = int(input('고객 포인트 입력 : '))
minAblePoint = 1000
if userPoint >= minAblePoint:
result = '가능'
else:
result = '불가능'
print('포인트 사용 가능 여부 : {}'.format(result))
userPoint = int(input('고객 포인트 입력 : '))
minAblePoint = 1000
if userPoint >= minAblePoint:
result = '가능'
else:
result = '불가능'
lackpoint = minAblePoint - userPoint
print('포인트가 {}점 부족합니다.'.format(lackpoint))
# 위의 두 줄은 조건문으로 변경하여 코딩하기 어려움
print('포인트 사용 가능 여부 : {}'.format(result))
exampleScore = int(input('시험 성적 입력 : '))
grade = ''
if exampleScore >= 90:
grade = 'A'
elif exampleScore >= 80:
grade = 'B'
elif exampleScore >= 70:
grade = 'C'
elif exampleScore >= 60:
grade = 'D'
else:
grade = 'F'
print('성적 : {}\t학점 : {}'.format(exampleScore, grade))
조건식 순서가 중요하다.
조건 범위를 명시한다.
자동차 배기량에 따라 세금을 부과한다고 할 때, 다음 표를 보고 배기량을 입력하면 세금이 출력되는 프로그램을 만들어 보자.
carDisplacement = int(input('자동차 배기량 입력 : '))
if carDisplacement < 1000:
print('세금 : 100,000원')
elif carDisplacement <2000 and carDisplacement >= 1000:
print('세금 : 200,000원')
elif carDisplacement <3000 and carDisplacement >= 2000:
print('세금 : 300,000원')
elif carDisplacement <4000 and carDisplacement >= 3000:
print('세금 : 400,000원')
elif carDisplacement <5000 and carDisplacement >= 4000:
print('세금 : 500,000원')
elif carDisplacement >= 5000:
print('세금 : 600,000원')
출퇴근 시 이용하는 교통 수단에 따라 세금을 감면해 주는 정책을 세우려고 한다. 다음 내용에 맞게 프로그램을 만들어 보자.
selectNum = int(input('출퇴근 대상지아신가요? 1.Yes\t2.No : '))
if selectNum == 1:
print('교통수단을 선택하세요.')
trans = int(input('1. 도보, 자전거\t2. 버스, 지하철\t3. 자가용\t: '))
if trans == 1:
print('세금 감면 5%')
elif trans == 2:
print('세금 감면 3%')
elif trans == 3:
print('추가 세금 1%')
elif selectNum == 2:
print('세금 변동 없습니다.')
else:
print('잘못 입력하셨습니다.')
횟수에 의한 반복
예시)
for i in range(100):
print('i -> {}'.format(i))
조건에 의한 반복
예시)
num = 0
while (num < 10):
print('num -> {}'.format(num))
num += 1
이상 데이터 취업 스쿨 Chpt.1 파이썬 기초의 저번 진도 이후의 스터디노트이다.
스케줄 정상화 작업이 아직 진행 중인 상태이다.
아무래도 velog 작성하면서 문법적인 면에서 배워야 하는 부분들이 많기에 작업 속도가 많이 느리다는 것을 느끼고 있다.
이번 강의에서 실습 문제를 풀면서 예시 답안을 설명하기 전에 먼저 직접 풀어보는 방식으로 공부를 진행하였다.
코드 작성 후 예시 답안과 비교하면서 어떤 부분에서 차이점이 보이는 지, 그리고 이를 통해 어떻게 코드 작성을 해야 하는지에 대하여 공부할 수 있는 기회가 되었다.
현재 새벽 6시 되기 2분 전이다.
스케줄 정상화가 빠르게 이루어지길 바랄 뿐이다.