목록2024/04/23 (30)
SeouliteLab
예제: import random def random_select_element(input_list): if not input_list: return None return random.choice(input_list) my_list = ["apple", "banana", "cherry", "date", "elderberry"] selected_element = random_select_element(my_list) if selected_element: print("선택된 요소:", selected_element) else: print("리스트가 비어 있습니다.") 설명: 위의 코드는 리스트에서 임의의 요소를 선택하는 방법을 보여줍니다. random_select_element 함수는 리스트를 입력받아서 해당..
예제: def read_file_into_list(file_name): try: with open(file_name, 'r') as file: lines = file.readlines() lines = [line.strip() for line in lines] return lines except FileNotFoundError: print(f"{file_name} 파일을 찾을 수 없습니다.") return None file_name = "sample.txt" lines = read_file_into_list(file_name) if lines: print(f"{file_name} 파일을 읽어온 결과:") for line in lines: print(line) 설명: 위의 코드는 파일을 한 ..
예제: print("Hello,", end=" ") print("World!") 설명: 위의 코드는 새 줄 없이 출력하는 방법을 보여줍니다. 기본적으로 print() 함수는 출력 후 자동으로 새 줄을 추가합니다. 하지만 end 매개변수를 사용하여 출력 끝에 추가할 문자열을 지정할 수 있습니다. 기본값은 개행 문자(\n)입니다. 예제에서는 "Hello,"를 출력한 후에 공백을 출력하고자 end=" "를 사용하여 출력을 마무리합니다. 그러면 다음 print() 함수가 이어서 공백 없이 출력됩니다. 이를 통해 한 줄에 여러 번 출력하는 경우에도 줄바꿈을 제어할 수 있습니다.
예제: def get_substring(input_string, start, end): if start len(input_string) or start >= end: return None return input_string[start:end] my_string = "Hello, World!" substring = get_substring(my_string, 7, 12) if substring is not None: print("부분 문자열:", substring) else: print("유효하지 않은 인덱스입니다.") 설명: 위의 코드는 문자열에서 부분 문자열을 가져오는 방법을 보여줍니다. get_substring 함수는 문자열과 부분 문자열의 시작 인덱스와 끝 인덱스를 입력받아서..
예제: def get_last_element(input_list): if input_list: return input_list[-1] else: return None my_list = [1, 2, 3, 4, 5] last_element = get_last_element(my_list) if last_element is not None: print("리스트의 마지막 요소:", last_element) else: print("리스트가 비어 있습니다.") 설명: 위의 코드는 리스트의 마지막 요소를 가져오는 방법을 보여줍니다. get_last_element 함수는 리스트를 입력받아서 해당 리스트의 마지막 요소를 반환합니다. 이때, 리스트의 인덱스 -1을 사용하여 마지막 요소를 가져옵니다. 함수 내부에서는 입력된..
예제: from datetime import datetime def convert_to_datetime(date_string, format): try: datetime_obj = datetime.strptime(date_string, format) return datetime_obj except ValueError: return None date_string = "2024-04-25 08:30:00" format = "%Y-%m-%d %H:%M:%S" datetime_obj = convert_to_datetime(date_string, format) if datetime_obj: print("변환된 날짜 및 시간:", datetime_obj) else: print("올바른 형식으로 입력하세요.") 설명:..
예제: class Color: RED = '\033[91m' GREEN = '\033[92m' YELLOW = '\033[93m' BLUE = '\033[94m' RESET = '\033[0m' def print_colored_text(text, color): colored_text = color + text + Color.RESET print(colored_text) print_colored_text("빨간색 텍스트", Color.RED) print_colored_text("초록색 텍스트", Color.GREEN) print_colored_text("노란색 텍스트", Color.YELLOW) print_colored_text("파란..
예제: def parse_string_to_number(string): try: number = float(string) # 부동소수점으로 변환 시도 if number.is_integer(): return int(number) # 정수로 변환 가능하면 정수 반환 else: return number # 부동소수점 반환 except ValueError: return None # 변환 실패 시 None 반환 string1 = "3.14" string2 = "42" string3 = "apple" result1 = parse_string_to_number(string1) result2 = parse_string_to_number(string2) result3 = parse_string_to_number(stri..
예제: def check_key(dictionary, key): if key in dictionary: print(f"'{key}' 키는 딕셔너리에 이미 존재합니다.") else: print(f"'{key}' 키는 딕셔너리에 존재하지 않습니다.") my_dict = {'apple': 3, 'banana': 5, 'orange': 2} check_key(my_dict, 'apple') check_key(my_dict, 'grape') 설명: 위의 코드는 주어진 딕셔너리에 특정 키가 이미 존재하는지 확인하는 함수를 구현한 예제입니다. check_key 함수는 두 개의 인자를 받습니다. 첫 번째 인자는 딕셔너리..
예제: def concatenate_lists(list1, list2): concatenated_list = list1 + list2 return concatenated_list list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] result = concatenate_lists(list1, list2) print("두 리스트를 연결한 결과:", result) 설명: 위의 코드는 두 개의 리스트를 연결하는 함수를 정의하고 호출하는 예제입니다. concatenate_lists 함수는 두 개의 리스트를 인자로 받아서 이를 연결한 새로운 리스트를 반환합니다. 이때, 파이썬의 + 연산자를 사용하여 두 리스트를 연결합니다. 그리고 나서 list1과 ..