본문 바로가기

Python/Python_basic60

날짜 포매팅 예제(from datetime import datetime) □ 현업에서 날짜 및 시간 포매팅은 중요한 요소중 하나임. 왜냐하면 log 관리기능을 위해 사용되기 때문임. □ 날짜계산, 수행시간계산, 로그 출력 포멧 규정등 프로그래밍에서 많이 활용됨 □ 참고 사이트 https://docs.python.org/ko/3/library/datetime.html#strftime-and-strptime-behavior datetime — Basic date and time types Source code: Lib/datetime.py The datetime module supplies classes for manipulating dates and times. While date and time arithmetic is supported, the focus of the imp.. 2023. 11. 13.
딕셔너리 조회 예제 (dictionary comprehension + input함수) #아래 Dict 데이터에서 사용자 입력으로 키(Key) 로 검색 후 값을 반환하시오 dict_data = {'USA' : 36, 'Germany' : 17, 'France' : 32, 'Australia' : 77, 'South Africa' : 99, 'India' : 108, 'South Korea' : 200} #예제 풀이① search_Keyword = input('국가명을 영문으로 입력해주세요(미국은 USA, 미국 제외한 국가는 첫글자만 대문자로 기재) : ') #input 함수 지정 #입력받은 값에 따라 if문사용 if search_Keyword in dict_data.keys(): print_value = dict_data.get(search_Keyword) print(f'풀이방법1 : 입력.. 2023. 11. 13.
타임 딜레이 □ 일정 시간을 지정하여, 지정된 시간만큼 간격으로 프로그램이 실행되도록 할 때 사용 □ 타임 라이브러리 호출 □ time.spleep(간격시간지정) #1부터 10까지 2초 간격으로 숫자를 출력 후 종료 import time #반복문 : for문 for i in range(1,11): time.sleep(2) #2초마다 출력 print(i) #반복문 : while문 n=0 while n=3.5: break #방법3 def sleep_out(n=1): #함수정의 print(f"Delayed for {n} Seconds") time.sleep(n) for n in [0.5,1, 1.5, 2, 2.5, 3, 3.5]: sleep_out(n) #함수호출 2023. 11. 8.
enumerate() □ enumerate() 파이썬 내장함수로 열거형 객체를 반환하고 카운터 변수도 추가해줌 □ enumerate(iterable, start = 시작값) ○ iterable 길이만큼 인덱스를 생성해줌 ○ start 값을 정하여 시작 인덱스를 지정 가능 □ 아래 한 개의 리스트를 딕셔너리형식으로 변환하시오 l= ["red","black","blue","orange","purple"] #방법1 d1 = dict(enumerate(l)) #enumerate + 형변환 print(d1) d2 = dict(enumerate(l, start=100)) #형변환 print(d2) d3 = dict(enumerate(l)) print(d3) 2023. 11. 8.
딕셔너리 ↔ 자료구조 형변환 #json.dumps(dict,indent) #json.dump(dict, file_pointer) #json으로 형변환 d = {"group1":[ {'name':'Park', 'age':'32', 'sex':'Male'}, {'name':'Cho', 'age':'44', 'sex':'Female'}, {'name':'Kang', 'age':'39', 'sex':'Female', 'married':'No'} ], "group2":[ {'name':'Kim', 'age':'23', 'sex':'Male', 'married':'Yes'}, {'name':'Lee', 'age':'37', 'sex':'Male', 'married':'No'} ], "type": {'a':'employee', 'b':'offi.. 2023. 11. 7.
딕셔너리 값 추출 예제2 #아래 딕셔너리에 group1에 {'name':'Park', 'age':'32', 'sex':'Male','married':'Yes'} 추가, type에 {'f':'engineer'} 추가 d = {"group1":[ {'name':'Park', 'age':'32', 'sex':'Male'}, {'name':'Cho', 'age':'44', 'sex':'Female'}, {'name':'Kang', 'age':'39', 'sex':'Female', 'married':'No'} ], "group2":[ {'name':'Kim', 'age':'23', 'sex':'Male', 'married':'Yes'}, {'name':'Lee', 'age':'37', 'sex':'Male', 'married':'No'}.. 2023. 11. 7.
딕셔너리 값 추출 예제1 #아래 딕셔너리에서 출력결과와 같이 값 추출 #Name : Kim, Age : 23, Type : office' d = {"group1":[ {'name':'Park', 'age':'32', 'sex':'Male'}, {'name':'Cho', 'age':'44', 'sex':'Female'}, {'name':'Kang', 'age':'39', 'sex':'Female', 'married':'No'} ], "group2":[ {'name':'Kim', 'age':'23', 'sex':'Male', 'married':'Yes'}, {'name':'Lee', 'age':'37', 'sex':'Male', 'married':'No'} ], "type": {'a':'employee', 'b':'office', .. 2023. 11. 7.
문자열 포멧팅 String Format Practices □ 문자출력(서식) 종류 多 □ % OPerator(old style) : 가독성 떨어짐 □ str.format(new Style) : 명시적임 □ f = Strings(python 3.6) : 직관적임 □ Template String(from string import Template) : 번거로움 □ 정렬 - ^:가운데, :오른쪽 #공통변수 선언 x = 10 y = 20 serialno = 308276567 n = 'Kim' #출력1 : % 문법 ex1 = 'n = %s, s = %d, sum = %d' %(n,serialno,(x+y)) print(ex1) #출력2 : .format함수 ex2 = 'n = {n}, s = {serialno}, sum = {sum}'.format(n=n, serialn.. 2023. 11. 7.
[Python] 사용자 입력 처리 Taking Multiple Inputs □ input() 함수 사용 □ input 함수를 사용해 받은 값은 무조건 str 형식임 □ 따라서 정수, 실수형태로 값을 받고자 할 시 input함수를 원하는 타입으로 감싸서 형변환을 시행해야함 #사용자 입력 처리 Taking Multiple Inputs #예제: 사용자에게 정수를 3회 입력 받은 후 평균 값을 구하시오 #방법1 #빈리스트 num_grp = [] #0인변수 start_num = 0 for i in range(0,3): num_value = int(input('정수를 입력해주세요 : '))#input함수는 string으로 받은 값을 int로 치환해야함 num_grp.append(num_value) num_avg = sum(num_grp) // len(num_grp) # / 실수 반환 , .. 2023. 11. 6.