Language/Python
sw교육_python 4일차
송 이
2023. 9. 14. 17:29
boolean type¶
- True | False
- 논리연산자 (not, and, or)
- 비교연산자 (~, &, |)
- '', [], {}, (), None, 0 -> False (비어있을때)
In [5]:
intValue01 = 5 #0100
intValue02 = 0 #0000
print('비교연산 - ', intValue01 & intValue02) #이진값으로 연산, 0100 & 0000 -> 0
print('비교연산 - ', intValue01 | intValue02)
비교연산 - 0 비교연산 - 5
In [7]:
lstTmp = []
strTmp = ''
dictTmp = {}
boolTmp = False
intTmp = 0
print(bool(lstTmp), bool(strTmp), bool(dictTmp), boolTmp, bool(intTmp))
False False False False False
In [8]:
lstTmp = [1,2]
strTmp = 'str'
dictTmp = {'key':'value'}
boolTmp = True
intTmp = 1
print(bool(lstTmp), bool(strTmp), bool(dictTmp), boolTmp, bool(intTmp))
True True True True True
In [11]:
print('논리연산자 - ')
trueTmp = True
falseTmp = False
print('and - ', trueTmp and falseTmp )
print('or - ', trueTmp or falseTmp )
print('not - ', not trueTmp)
논리연산자 - and - False or - True not - False
프로그램의 흐름을 제어하는 제어구문과 반복문¶
- 제어구문(if ~, if ~ in)
- 반복구문(for ~)
- 블럭을 의미하는 기호 :
- 들여쓰기 주의 (indentation)
In [15]:
print('제어구문 - ')
if True :
pass
else :
pass
if True :
pass
elif True :
pass
elif True :
pass
#중첩문
if True :
if True :
pass
else :
pass
else :
pass
제어구문 -
In [19]:
if True :
print('Good')
else :
print('Bad')
Good
In [24]:
score = int(input('점수를 입력하세요'))
print(score)
if score >= 60 :
print('pass')
else :
print('nonpass')
점수를 입력하세요90 90 pass
In [25]:
#input 함수를 이용하여 점수를 입력받아 학점을 출력하는 제어구문을 작성하시오
#60 미만이면 F학점
In [30]:
score = int(input('점수를 입력하세요'))
print(score)
if score >= 90 :
if score >= 95 :
print('A+')
else :
print('A')
elif score >= 80 :
print('B')
elif score >= 70 :
print('C')
elif score >= 60 :
print('D')
else :
print('F')
점수를 입력하세요93 93 A
In [32]:
areas = ['서울','경기','부산']
region = input('지역을 입력하세요 : ')
if region in areas :
print('존재')
else :
print('{} 지역은 대상이 아닙니다.'.format(region))
지역을 입력하세요 : 광주 광주 지역은 대상이 아닙니다.
In [36]:
dictTmp = {'melon':100, 'bravo':200,'bibibig':300}
target = 'banana'
if target in dictTmp :
print(dictTmp[target])
else :
print('{} 키는 존재하지 않음'.format(target))
banana 키는 존재하지 않음
- 돌발퀴즈
- 연산자 %, ==, and, or
- 윤년의 조건 : 4의 배수이고 100의 배수가 아니거나 400의 배수일 때
- input 함수를 이용해서 년도를 입력받아 윤년인지 아닌지를 판단하고 싶다면?
In [40]:
year = int(input('연도를 입력하세요 : '))
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 :
print('윤년입니다')
else :
print('윤년이 아닙니다')
연도를 입력하세요 : 2000 윤년입니다
- 돌발퀴즈(확장)
- input 함수를 이용해서 년도, 월을 입력받아서 월의 마지막 날을 출력하라
In [47]:
#나의 답
year = int(input('연도를 입력하세요 : '))
month = int(input('월을 입력하세요 : '))
mon1 = [1,3,5,7,8,10,12]
mon2 = [2]
mon3 = [4,6,9,11]
if month in mon1 :
print('{}월의 마지막날은 31일입니다.'.format(month))
elif month in mon2 :
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 :
print('{}월의 마지막날은 29일입니다.'.format(month))
else :
print('{}월의 마지막날은 28일입니다.'.format(month))
else :
print('{}월의 마지막날은 30일입니다.'.format(month))
연도를 입력하세요 : 2021 월을 입력하세요 : 2 2월의 마지막날은 28일입니다.
In [50]:
#강사님 답
yearMonths = [31,28, 31,30,31,30,31,31,30,31,30,31]
leapYearMonths = [31,29, 31,30,31,30,31,31,30,31,30,31]
year = int(input('연도를 입력하세요 : '))
month = int(input('월을 입력하세요 : '))
if((year % 4 == 0) and (year % 100 != 0)) :
print('{}년 {}월의 마지막날은 {}일 입니다.'.format(year,month,leapYearMonths[month-1]))
elif year%400 == 0 :
print('{}년 {}월의 마지막날은 {}일 입니다.'.format(year,month,leapYearMonths[month-1]))
else :
print('{}년 {}월의 마지막날은 {}일 입니다.'.format(year,month,yearMonths[month-1]))
연도를 입력하세요 : 2020 월을 입력하세요 : 2 2020년 2월의 마지막날은 29일 입니다.
- date, datetime 날짜관련 모듈이 있다.
- xxxx.py(module) - 변수, 함수, 클래스
- import, from ~ import
- package : 여러개의 모듈을 묶는 것
- 함수 < 모듈 < 패키지
- 형식) import 모듈
- 형식) from 패키지.모듈 import 함수 , 클래스
- 형식) from 패키지 import 모듈
- 형식) from 모듈 import 함수 , 클래스
In [63]:
from datetime import date, datetime
today = date.today()
print('dir - ', dir(today))
print('today - ', today)
print(today.year, today.month, today.day)
today = datetime.today()
print(today)
dir - ['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'ctime', 'day', 'fromisocalendar', 'fromisoformat', 'fromordinal', 'fromtimestamp', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'min', 'month', 'replace', 'resolution', 'strftime', 'timetuple', 'today', 'toordinal', 'weekday', 'year'] today - 2023-09-06 2023 9 6 2023-09-06 13:15:29.495785
In [74]:
#날짜에 대한 연산을 도와주는 함수
from datetime import timedelta #day 연산 가능
from dateutil.relativedelta import relativedelta #연,월,일 연산 가능
today = date.today()
day = timedelta(days = 100)
print(today + day)
day = relativedelta(days = 1)
month = relativedelta(months = 1)
year = relativedelta(years = 2 )
#print(today + year, today+month, today+day)
today = today + year
today = today + month
today = today + day
print(today)
2023-12-15 2025-10-07
In [93]:
print('문자 -> 날짜')
strDate = '2023-09-06'
print(type(strDate))
castingDate = datetime.strptime(strDate, '%Y-%m-%d')
print(castingDate, type(castingDate))
print('날짜 - > 문자')
print(castingDate.strftime('%Y-%m-%d'), type(castingDate.strftime('%Y-%m-%d')))
문자 -> 날짜 <class 'str'> 2023-09-06 00:00:00 <class 'datetime.datetime'> 날짜 - > 문자 2023-09-06 <class 'str'>
In [103]:
year = int(input('년도 입력하세요 : '))
month= int(input('월 입력하세요 : '))
yearMonth = '{}-{}'.format(year, month + 1)
print('input date - ', yearMonth, type(yearMonth))
yearMonthDate = datetime.strptime(yearMonth , '%Y-%m')
print('casting date - ', yearMonthDate, type(yearMonthDate))
lastDay = yearMonthDate - relativedelta(days = 1) #이전달의 라스트데이
lastDay = lastDay.day
print('lastday - ', lastDay)
print('{}년 {}월의 마지막날은 {}일 입니다.'.format(year,month,lastDay))
년도 입력하세요 : 2023 월 입력하세요 : 9 input date - 2023-10 <class 'str'> casting date - 2023-10-01 00:00:00 <class 'datetime.datetime'> lastday - 30 2023년 9월의 마지막날은 30일 입니다.
- 3항 연산자 : (조건식) : 참 : 거짓
- python : 참 if (조건식) else 거짓
In [109]:
tmp = 9
if tmp >= 5 :
print(tmp *2)
else :
print(tmp +2)
result = tmp * 2 if tmp >= 5 else tmp + 2 #3항연산자 if문
print(result)
18 18
- 돌발퀴즈
- 011 SK, 016 KT, 019 LG
- input함수로 011-xxxx-xxxx
- 통신사를 판단하고 싶다면?
- 출력예시 ) 당신이 사용하는 통신사는 SK 입니다.
In [120]:
num = input('휴대폰 번호를 입력하세요 : ')
print(num)
if num[0:3] == '011' :
print('당신이 사용하는 통신사는 SK입니다.')
elif num[0:3] == '016' :
print('당신이 사용하는 통신사는 KT입니다.')
else :
print('당신이 사용하는 통신사는 LG입니다.')
print('당신이 사용하는 통신사는 SK입니다.') if num[0:3] == '011' else print('당신이 사용하는 통신사는 KT입니다.') if num[0:3] == '016' else print('당신이 사용하는 통신사는 LG입니다.')
휴대폰 번호를 입력하세요 : 01639472948 01639472948 당신이 사용하는 통신사는 KT입니다. 당신이 사용하는 통신사는 KT입니다.
In [122]:
phoneNumber = input('번호를 입력하세요 : ')
print('number -', phoneNumber, type(phoneNumber))
brand = phoneNumber.split('-')[0]
if brand == '011' :
print('당신이 사용하는 통신사는 SK입니다.')
elif brand == '016' :
print('당신이 사용하는 통신사는 KT입니다.')
else :
print('당신이 사용하는 통신사는 LG입니다.')
번호를 입력하세요 : 01483948294 number - 01483948294 <class 'str'> 당신이 사용하는 통신사는 LG입니다.
In [130]:
lstTmp = [10,20,30]
dictTmp = {'name':'seop','address':'busan'}
setTmp = {10,12,24}
tupleTmp = (1,2,3,4)
if 'Busan'.lower() not in dictTmp.values() :
print('TRUE')
else :
print('FALSE')
if 1 in tupleTmp :
print('TRUE')
else :
print('FALSE')
FALSE TRUE
- 관계연산자 : > , >= , < , <= , ==, !=
In [134]:
x = 15
y = 10
print('== 양변이 같을 때', x == y)
print('!= 양변이 다를 때' , x != y)
print('> 왼쪽이 클 때' , x > y)
print('>= 왼쪽이 크거나 같을 때' , x >= y)
== 양변이 같을 때 False != 양변이 다를 때 True > 왼쪽이 클 때 True >= 왼쪽이 크거나 같을 때 True
In [141]:
print('연산자는 우선순위 가진다 -')
print('산술 > 관계 > 논리')
print(3+4 > 7+3)
print(5+10>3) and (7+3 == 10)
score = 90
grade = 'A'
if score >= 90 and grade == 'A' :
print('pass')
연산자는 우선순위 가진다 - 산술 > 관계 > 논리 False True pass
In [2]:
value = int(input('값을 입력하세요 : '))
print(value)
if value-20 < 0 :
print(0)
elif value-20 > 255 :
print(255)
else :
print(value - 20)
값을 입력하세요 : 40 40 20
In [11]:
inputTime = input('현재시간 : ')
print(inputTime[-1:-3])
if inputTime[-2:] == '00' :
print('정각입니다.')
else :
print('정각이 아닙니다.')
현재시간 : 03:00 정각입니다.
In [14]:
fruitName = input('과일이름을 입력하세요 : ')
fruit = ['사과','포도','홍시']
if fruitName in fruit :
print('정답입니다.')
else :
print('오답입니다.')
과일이름을 입력하세요 : 딸기 오답입니다.
In [32]:
address = input('우편번호를 입력하세요 : ')
kang = ['0','1','2']
dobong = ['3','4','5']
nowon = ['6','7','8','9']
print(address[2])
if address[2] in kang :
print('강북구')
elif address[2] in dobong :
print('도봉구')
else :
print('노원구')
우편번호를 입력하세요 : 013000 3 도봉구
In [31]:
user = input('주민등록번호 입력 : ')
if user[-7] == '1' or user[-7] == '3' :
print('남자')
else :
print('여자')
주민등록번호 입력 : 292929-2939494 여자
In [ ]:
user = input('주민등록번호 입력 : ')
busan = ['09','10','11','12']
if user[8:10] in busan :
print('서울 출생이 아닙니다')
else :
print('서울 출생입니다.')
#print('서울') if int(user.split('-')[1][1:3]<=8 else print('다른 지역입니다'))
In [41]:
inputValue = input('종목명을 입력하세요 : ')
warnInvestmentLst = ["Microsoft", "Google", "Naver", "Kakao", "SAMSUNG", "LG"]
if inputValue in warnInvestmentLst :
print('투자 경고 종목입니다.')
else :
print('투자 경고 종목이 아닙니다')
종목명을 입력하세요 : kakao 투자 경고 종목이 아닙니다
In [25]:
fruit = {"봄" : "딸기", "여름" : "토마토", "가을" : "사과"}
inputValue = input('입력하세요 : ')
if inputValue in fruit.keys() :
print('정답입니다.')
else :
print('오답입니다')
입력하세요 : 사과 오답입니다
In [15]:
#문제09
char = input('문자를 입력하세요 : ')
char.islower()
if char.islower() :
print(char.upper())
else :
print(char.lower())
문자를 입력하세요 : A a
In [17]:
score = int(input('점수를 입력하세요 : '))
if score >= 81 and score <= 100 :
print('A')
elif score >= 61 and score <= 80 :
print('B')
elif score >= 41 and score <= 60 :
print('C')
elif score >= 21 and score <= 40 :
print('D')
else :
print('E')
점수를 입력하세요 : 88 A
In [1]:
#문제11
num01 = int(input('number : '))
num02 = int(input('number : '))
num03 = int(input('number : '))
if num01 > num02 and num01 > num03 :
print(num01)
elif num02 > num01 and num02 > num03 :
print(num02)
else :
print(num03)
number : 10 number : 20 number : 30 30
In [19]:
num = int(input('숫자를 입력하세요 : '))
if num % 2 == 0 :
print('짝수입니다')
else :
print('홀수입니다')
숫자를 입력하세요 : 5 홀수입니다