#datetime에서 날짜만 확인 date() -> date 객체 반환 #datetime에서 시간만 확인 time() ->time 객체 반환 nowdate = datetime.datetime.now().date() nowtime = datetime.datetime.now().time()
print("NOWDATE:", nowdate, type(nowdate)) print("NOWTIME:", nowtime, type(nowtime)) #date 객체는 datetime이 가진 year, month, day 등 날짜 관련 속성들을 가지고 있다 #time 객체는 datetime이 가진 시간 관련 속성과 메서드들을 그대로 사용
def handling_exception(): """ 예외 처리 연습 """ # 인덱스 에러 IndexError # 캐스팅 에러 ValueError # 사전 키 접근 에러 KeyError # 정수를 0으로 나눴을 경우 ZeroDivisionError lst =[] try: #lst[3] =1 #IndexError 4/1 #ZeroDivisionError #int("String") # valueError except ValueError as e: print("정수로 변환할 수 없어요.", e) except ZeroDivisionError as e: print("정수를 0으로 나눌 수 없어요.", e) except IndexError as e: print("인덱스 범위가 벗어났습니다.", e) except Exception as e: #Exception은 모든 예외의 부모 클래스 print("Exception:", e) else: print("예외없이 코드가 실행되었습니다.")
finally: print("예외 여부 관계 없이 항상 마지막에 실행")
def raise_exception(): def beware_dog(animal): if animal.lower() == "dog": # 강제 익셉션 발생 raise RuntimeError("강아지는 출입을 제한합니다.") else: print("어서오세요!") try: beware_dog("cow") beware_dog("cat") beware_dog("dog") except Exception as e: print(e, type(e))
if __name__ =="__main__": handling_exception() raise_exception()
#함수의 스코핑 룰 #local -> Enclosed -> Global -> Builtin x = 1 #Global 영역 def scope_func(a): print("scope_func:", locals()) #a-> 외부로부터 넘어온 객체가 local 심볼에 할당 # x-> 로컬이 아니다 print("x is in global?", "x" in globals()) return a+x
scope_func(10)
def scope_func2(a): x = 2 #global x와 다른 객체다 print("scope_func2:", locals()) return a+x
print(scope_func2(10))
def scope_func3(a): #rmffhqjf rorcpfmf gkatn soqndptj tkdydgkrhwk gkf ruddn #global 키워드 사용 global x #지금부터 사용할 x는 로컬로 만들지 않고 글로벌 객체를 사용할 것을 선언 #주의 : 가능하면 글로벌 객체를 내부에서 변경하지 않을 것을 권장 # 어디에서 글로벌 객체가 변경되쓴건지 추적이 힘들기 때문이에요 x = 3 print("scope_func2:", locals()) return a + x
print(scope_func3(10)) print("x:",x) #global영역 #함수의 선언(주로 가변인자와 키워드 인자 중심으로 정리) #프로그래밍에서의 함수는 기능의 집합 # 입력값이 없을 수도 있고, 출력이 없을 경우도 있다 # 함수를 종료할 때는 return # return 뒤에 반환값을 명시하면 결과를 받을 수 있다 # 값을 return 하지 않았거나 끝날때까지 아무 return도 없는 경우 # ->None (Java의 Null과 비슷하다) def times(a,b): return a*b
#함수 자체도 객체로 판단 # 다른 식별자에 할당할 수 있고 # 다른 함수의 인수로 전달할 수 있다 fun = times
print("fun:", type(fun)) # 객체가 호출 가능한 객체인지(함수) 판별하려면 callable 함수 print("is fun callable?", callable(fun))
# 만약 객체가 함수인지 판별한 이후에 호출 if callable(fun): print(fun(10,20))
# 인수의 기본값 def incr(a, step=1): # 두번째 인자값은 1이 기본값이다 return a+step
print(incr(10)) #두번째 인자 step이 기본값을 가지고 있으므로 기본값으로 세팅 print(incr(10,2)) # 기본값을 무시하고 새로운 값을 할당 #기본적으로 python은 인수의 이름을 명시해서 인자를 전달할 수 있다 #인자의 순서가 중요하지 않게 된다 print(incr(step=3, a=10))
#가변 인수 # 정해지지 않은 개수의 인자를 받을 때 # 가변 인자를 받을 변수의 앞에 * 명시 # -> 순차 자료형으로 변환되어 입력 #연습 : 여러개의 인자를 넘겨 받아서 해당 인자가 int, float이면 합산 # 그렇지 않으면 합산에서 제외 합계를 return def get_total(*args): total = 0 print(args, type(args)) for x in args: # 합산 가능한 타입인지 체크 if isinstance(x, (int, float)): total += x return total
# 고정인자와 가변인자 키워드 인자 # 순서가 중요 # 고정인자 -> 가변인자(*) -> 키워드 인자(**) def func_args(a,b, *args, **kwd): # a, b는 고정인자 : 반드시 넘겨줘야 한다 # 그 뒤에 나온 인자의 목록은 args로 넘어올 것(tuple) # 그 뒤에 나온 인자는 키워드(dict) print("고정인자:", a,b) print("가변인자:", args) print("키워드 인자:", kwd) if "option1" in kwd: print("option 1이 {}로 설정되었습니다.".format(kwd['option1'])) else: print("option1이 설정되지 않았습니다.") func_args(1,2,3,4,5,6, option1="옵션1", option2="옵션2")
#함수도 객체이므로 다른 함수의 인자로 넘겨줄 수 있다 # Callback 패턴 구현 def calc(a,b, func): # 계산을 위한 수 2개 # 계산 식 함수 func 를 전달 # 넘겨 받은 func가 호출 가능 객체인지 확인 if callable(func): #func은 함수? return func(a,b) #계산 함수는 외부로부터 주입 def plus(a,b): return a+b def minus(a,b): return a-b
# lambda 함수 : 익명 함수 print(calc(10,20,lambda a, b: a*b)) # 즉석에서 곱셈함수 전달 # lambda 함수를 이용한 sort(sorted) 키 함수 정의 words = "Life is too short, you need Python".upper().replace(",","").split() print("WORDS:", words) # SORT 할 때 정렬 기준 key 함수를 lambda로 전달 # 단어 길이의 역순 정렬 함수를 람다로 sorted_words = sorted(words, key=lambda word: len(word), reverse=True) print("Sorted Words:", sorted_words)
# 1부터 20까지 수열을 4로 나누었을 때의 나머지 순으로 정렬 nums = range(1,21) # 20까지 print("nums:", list(nums)) print("SORTED num % 4 ASC:", sorted(nums, key=lambda n: n % 4))
# 흐름 제어 ( 조건문, 반복문) def if_statement(): """ 조건문 """ #키보드로부터 금액을 입력받고 # 10000원 이상이면 by taxi # 2000원 이상이면 by bus # 그렇지 않으면 on foot 출력 print("==== if elif else") #키보드에서 금액 입력 money = input("얼마 가지고 있어?") money = int(money) # int로 변환 message = "" if money >= 10000: message = "by taxi" elif money >= 2000: message = "by bus" else: message = "on foot" print("가지고 있는 돈 {}, 이동 방법 {}".format(money, message))
def if_expr(): """ 조건 표현식""" print("==== if expression") money = int(input("얼마 가지고 있어?"))
message = "by taxi" if money >=10000 \ else "by bus" if money >= 2000 \ else "on foot" print("가지고 있는 돈 {}, 이동 방법 {}".format(money, message))
def for_ex(): """for 반복문""" # 인덱스 반복 구문은 없고 # 순차자료형의 각 요소를 순회하는 Loop a = ["개", "고양이", "소", "말"] for animal in a: print("item:" , animal) else: print("루프가 종료되지 않고 정상 종료되었을 때 단 한번 실행된다") # 상황 2: 값과 함께 인덱스도 필요한 경우 # enumerate 함수 -> (인덱스, 요소값) 튜플 for animal in enumerate(a): print(animal[0], animal[1])
for index, animal in enumerate(a): print("{}번째 동물 {}".format(index, animal))
# 상황 3: dict의 순회 ->key 목록을 loop dct = {"name": "홍길동", "age": 23, "job": "도적"} for key in dct: # 사전에 키가 할당 print("KEY: {} -> VALUE: {}".format(key,dct[key]))
# 상황 4 : dict 순회, key와 value가 함게 필요한 경우 for key, value in dct.items(): #(key, value) 쌍튜플 print("KEY: {} -> VALUE:{}".format(key, value))
# 상황 5: 범위의 loop -> range(시작, 끝경계, 간격) r = range(1, 101) # 1~ 100까지의 수 중 짝수의 합 total = 0 for num in r: if num % 2 == 0: total += num
print("1~100 짝수의 합:", total)
# 연습 문제1. 구구단을 출력 # 연습문제 2. 삼각형을 그려주세요 """ **** *** ** * """ #continue : 아래에 남아있는 문장은 더이상 실행하지 않고 다음번 loop로 이동 # break : 루프를 더이상 진행하지 않고 루프 밖으로 탈출 def while_ex(): # 특정 조건이 만족되는 동안 루프를 실행 # 조건을 True로 부여하면 무한 루프가 생성된다 # 1부터 100까지 숫자 중에서 짝수만 합산(While 버전) i = 1 total =0 while i<= 100: if i % 2 == 0: total += i i += 1 else: print("루프가 정상 종료되면 실행") print(total)
def list_comp(): """List Comprehension""" # 기존 순차자료형을 기반으로 조건에 맞는 데이터를 추출 # 연산식을 수행하여 새로운 리스트를 만들어 낸다 # Synyax: [표현식 for 항목 in 순회가능 객체 if 조건] # 기존 방식 data = range(1,11) # data 객체를 제곱해서 새 리스트를 만들자 results = [] for num in data: results.append(num * num) print("RESULT:", results) results = []
#리스트 내포 방식 results = [num*num for num in data] print("Result(내포):", results)
#내포시 if 표현식을 연결하면 조건에 맞는 데이터만 추출 할 수 있다 # 연산에 포함시킬 수 있다 words = "a as bat cat dove python".split() #list print("WORDS:", words) # words(str list)에서 요소의 길이가 3글자 이상인 # 요소들만 추출 새 리스트를 만들자 filtered = [word.upper() for word in words if len(word) >=3 ] print("Filtered Words:", filtered)
#연습 문제 # 1~ 100까지의 수 중에서 짝수의 리스트를 새로 만들기 number = range(1,101) filtered = [num*1 for num in number if num % 2 == 0] print(filtered)
def set_comp(): """ Set Comprehension """ # Syntax : { 표현식 for 객체 in 순회가능 객체 } # 예1: words 내에서 길이가 2글자 이하인 새로운 세 words =" a as bat cat dove python".split() filtered = { word.upper() for word in words \ if len(word) <= 2} print("filtered set:", filtered)
# 예2: 문자열 리스트에서 문자열의 길이를 set으로 저장 filtered = { len(word) for word in words } print("filtered set(length):", filtered)
def dict_comp(): #comp = comprehension(이해력) """ 사전의 내포 """ # Syntax: {키표현식: 값표현식 for 객체 in 순회가능객체} words = "Life is too short You need Python".upper().split() print("WORDS:",words) #키로는 개별 단어, 값으로는 해당 단어의 길이 dct = {word:len(word) for word in words} print(dct) if __name__ == "__main__": #if_statement() #if_expr() #for_ex() #while_ex() #list_comp() #set_comp() dict_comp()