Python
-
재귀호출Python 2023. 10. 17. 09:49
재귀호출 사용 >>> def hello(): ... print('hello, world') ... hello() ... >>> hello() # 실행 결과 hello, world hello, world hello, world hello, world hello, world hello, world hello, world hello, world hello, world hello, world hello, world hello, world hello, world hello, world Traceback (most recent call last): File "", line 1, in File "", line 3, in hello File "", line 3, in hello File "", line 3, in he..
-
위치 인수와 키워드 인수 사용Python 2023. 10. 16. 17:02
위치지 연습 문제 예제 # 30.6번 연습문제: 가장 높은 점수 구하는 함수 만들기 # 다음 소스 코드를 완성하여 가장 높은 점수가 출력되게 만드세요 kor, eng, mat, sci = 100, 86, 81, 91 def get_max_score(*args): return max(args) max_score = get_max_score(kor, eng, mat, sci) print('높은 점수:', max_score) max_score = get_max_score(eng, sci) print('높은 점수:', max_score) print() # 실행 결과 높은 점수: 100 높은 점수: 91 # 30.7번 심사문제: 가장 낮은 점수, 높은 점수와 평균 점수를 구하는 함수 만들기 # 표준 입력으로 국어..
-
함수 사용Python 2023. 10. 16. 12:33
함수는 def에 함수 이름을 지정하고 ()(괄호)와 :(콜론)을 붙인 뒤 다음 줄에 원하는 코드를 작성 > 반드시 들여쓰기 def는 정의하다의 define 함수 작성 및 호출 def hello(): print('Hello, world!') hello() 함수 결과 반환 def add(a, b): """이 함수는...""" return a + b x = add(10, 20) print(x) print(add.__doc__) add 함수에 "(큰따옴표) 세 개로 독스트링(설명) 추가 > 함수를 호출해도 독스트링은 출력되지 않음 함수의 __doc__으로 독스트링 출력 def add(a, b): result = a + b return result x = add(10, 20) print(x) # 출력 값 30 d..
-
회문 판별과 N-gram 만들기Python 2023. 10. 11. 16:58
회문 판별 회문: 거꾸로 읽어도 제대로 읽은 것과 같은 단어와 문장 ex) level, sos... etc # 반복문으로 문자 검사 word = input('단어 입력: ') is_palindrome = True for i in range(len(word) // 2): if word[i] != word[-1 - i]: is_palindrome = False break print(is_palindrome) # 실행 결과 단어 입력: hello (입력) False 단어 입력: level (입력) True N-gram 만들기 N-gram: 문자열에서 N개의 연속된 요소를 추출하는 방법 text = 'hello' # 2-gram이므로 문자열의 끝에서 한 글자 앞까지만 반복 for i in range(len(te..
-
filePython 2023. 10. 11. 15:09
파일에 문자열 쓰기, 읽기 # 파일 쓰기 file = open('hello.txt', 'w') file.write('Hello, world!') file.close() # 파일 읽기 f = open('hello.txt', 'r') s = f.read print(s) f.close() # 자동으로 파일 객체 닫기 with open('hello.txt', 'r') as f: s = f.read() print(s) 문자열 여러 줄을 파일에 쓰기, 읽기 # 반복문으로 문자열 여러 줄을 파일에 쓰기 with open('hello.txt', 'w') as file: for i in range(3): file.write( 'Hello, world! {0}\n'.format(i) ) Hello, world! 0 # 출..
-
setPython 2023. 10. 11. 14:04
집합을 표현하는 세트(set) 자료형으로 합집합, 교집합, 차집합 등의 연산 가능 >>> fruits = {'strawberry', 'grape', 'orange', 'pineapple', 'cherry'} >>> fruits {'cherry', 'pineapple', 'strawberry', 'grape', 'orange'} >>> fruits = {'orange', 'orange', 'cherry'} >>> fruits {'cherry', 'orange'} 요소의 순서가 정해져 있지 않아 출력할 때마다 요소의 순서가 다르게 나옴 요소 중복될 수 없음 >>> fruits['cherry'] Traceback (most recent call last): File "", line 1, in TypeError..
-
딕셔너리 응용Python 2023. 10. 10. 17:27
딕셔너리 만들기 기본 >>> d1 = dict( name='cat', age=3 ) >>> print(d1) {'name': 'cat', 'age': 3} >>> >>> d2 = dict( zip(['name', 'age'], ['cat', 3]) ) >>> print(d2) {'name': 'cat', 'age': 3} >>> >>> d3 = dict( [('name', 'cat'), ('age', 3)] ) >>> print(d3) {'name': 'cat', 'age': 3} >>> >>> d4 = dict( {'name':'cat', 'age':3} ) >>> print(d4) {'name': 'cat', 'age': 3} 딕셔너리 응용 >>> # 딕셔너리에 키-값 쌍 추가, 기본값 저장 >>> ..
-
문자열 응용Python 2023. 10. 10. 12:45
문자열 조작 >>> # 문자열 바꾸기 replace('바꿀문자열', '새문자열') >>> 'Hello, world!' .replace('world', 'Python') 'Hello, Python!' >>> # 바꾼 문자열 유지 >>> s = 'Hello, world!' >>> s = s.replace('world', 'Python') >>> print(s) Hello, Python! >>> >>> # 문자 바꾸기 str.maketrans('바꿀문자', '새문자') >>> table = str.maketrans('aeiou', '12345') >>> 'apple'.translate(table) '1ppl2' >>> >>> # 문자열 분리하기 >>> 'apple pear grape pineapple oran..