Python의 입출력, 제어문, 함수, 커맨드라인 인터페이스(CLI)를 모두 아우르는 두 가지 예제

예제 1: 간단한 할일 목록(Todo List) 프로그램

이 예제는 파일 입출력, 조건문, 반복문, 함수, CLI를 포함하여 Python의 기본적인 기능을 종합적으로 활용할 수 있습니다.

요구사항

  1. 사용자가 할일을 추가, 삭제, 조회할 수 있는 프로그램을 작성합니다.
  2. 프로그램 실행 시 명령어를 입력받아 동작합니다.
  3. 할일 목록은 파일에 저장되고, 프로그램 시작 시 파일에서 로드됩니다.

구현 단계

  1. 할일 목록을 저장할 파일을 읽고 쓰는 함수 작성
  2. 할일 추가, 삭제, 조회 기능을 제공하는 함수 작성
  3. CLI 인터페이스를 구현하여 사용자의 명령어를 처리

코드 예시

TODO_FILE = 'todo_list.txt'

def load_todos():
    todos = []
    try:
        with open(TODO_FILE, 'r') as file:
            for line in file:
                todos.append(line.strip())
    except FileNotFoundError:
        pass
    return todos

def save_todos(todos):
    with open(TODO_FILE, 'w') as file:
        for todo in todos:
            file.write(todo + '\n')

def add_todo():
    todo = input("할일을 입력하세요: ")
    todos = load_todos()
    todos.append(todo)
    save_todos(todos)
    print("할일이 추가되었습니다.")

def delete_todo():
    todo = input("삭제할 할일을 입력하세요: ")
    todos = load_todos()
    if todo in todos:
        todos.remove(todo)
        save_todos(todos)
        print("할일이 삭제되었습니다.")
    else:
        print("해당 할일이 목록에 없습니다.")

def list_todos():
    todos = load_todos()
    print("\n현재 할일 목록:")
    for todo in todos:
        print("- " + todo)

def main():
    while True:
        print("\n명령어를 입력하세요 (add, delete, list, exit): ", end="")
        command = input().strip().lower()

        if command == 'add':
            add_todo()
        elif command == 'delete':
            delete_todo()
        elif command == 'list':
            list_todos()
        elif command == 'exit':
            print("프로그램을 종료합니다.")
            break
        else:
            print("알 수 없는 명령어입니다.")

if __name__ == "__main__":
    main()

예제 2: 간단한 계산기 프로그램

이 예제는 함수, 조건문, 반복문, CLI를 사용하여 간단한 계산 기능을 구현할 수 있습니다.

요구사항

  1. 사용자가 두 수를 입력하고, 덧셈, 뺄셈, 곱셈, 나눗셈을 수행할 수 있는 프로그램을 작성합니다.
  2. 프로그램 실행 시 명령어를 입력받아 동작합니다.
  3. 계산 결과를 화면에 출력합니다.

구현 단계

  1. 사칙연산을 수행하는 함수 작성
  2. 사용자로부터 입력을 받아 사칙연산을 수행하는 CLI 인터페이스 구현

코드 예시

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return "0으로 나눌 수 없습니다."
    return a / b

def main():
    while True:
        print("\n명령어를 입력하세요 (add, subtract, multiply, divide, exit): ", end="")
        command = input().strip().lower()

        if command in ['add', 'subtract', 'multiply', 'divide']:
            try:
                a = float(input("첫 번째 숫자를 입력하세요: "))
                b = float(input("두 번째 숫자를 입력하세요: "))
            except ValueError:
                print("유효한 숫자를 입력하세요.")
                continue

            if command == 'add':
                result = add(a, b)
            elif command == 'subtract':
                result = subtract(a, b)
            elif command == 'multiply':
                result = multiply(a, b)
            elif command == 'divide':
                result = divide(a, b)

            print(f"결과: {result}")

        elif command == 'exit':
            print("프로그램을 종료합니다.")
            break
        else:
            print("알 수 없는 명령어입니다.")

if __name__ == "__main__":
    main()

+ Recent posts