학습 목표

  • 지금까지 배운 변수, 조건문, 반복문, 함수, 파일 입출력을 종합적으로 활용해본다.
  • 간단한 텍스트 기반 미니 프로젝트를 스스로 구현해보는 경험을 한다.

미니 프로젝트 기획 & 구성 이해하기

11.1 프로젝트 주제: “학생 정보 관리 프로그램”

  • 이름, 나이, 좋아하는 과목, 점수를 입력받아 저장
  • 모든 학생 정보를 파일에서 불러와 출력
  • 메뉴 선택으로 기능을 분기 (조건문 사용)

저장 파일 구조

파일명: students.txt 형식 예시:

이름: 주연, 나이: 13, 과목: 수학, 점수: 95
이름: 민수, 나이: 14, 과목: 과학, 점수: 88

11.2 기능 구성 설계

[1] 학생 정보 추가
[2] 전체 학생 정보 출력
[3] 프로그램 종료
  • 선택지 입력 후 분기 (if, elif, else)
  • 파일 저장은 append 방식으로 추가

11.3 기본 뼈대 작성

while True:
    print("\n[1] 정보 추가 [2] 전체 출력 [3] 종료")
    choice = input("메뉴를 선택하세요: ")

    if choice == "1":
        pass  # 정보 입력 및 저장
    elif choice == "2":
        pass  # 파일에서 정보 읽기
    elif choice == "3":
        print("프로그램을 종료합니다.")
        break
    else:
        print("잘못된 입력입니다.")

전체 코드 구현 및 실습

11.4 [1] 학생 정보 추가 기능

if choice == "1":
    name = input("이름: ")
    age = input("나이: ")
    subject = input("좋아하는 과목: ")
    score = input("점수: ")

    with open("students.txt", "a") as f:
        f.write(f"이름: {name}, 나이: {age}, 과목: {subject}, 점수: {score}\n")
    print("학생 정보가 저장되었습니다.")

11.5 [2] 전체 정보 출력 기능

if choice == "2":
    try:
        with open("students.txt", "r") as f:
            print("\n[전체 학생 정보]")
            print(f.read())
    except FileNotFoundError:
        print("아직 저장된 정보가 없습니다.")

11.6 전체 코드 통합

# 학생 정보 관리 프로그램

while True:
    print("\n===== 학생 정보 관리 프로그램 =====")
    print("[1] 학생 정보 추가")
    print("[2] 전체 학생 정보 출력")
    print("[3] 프로그램 종료")

    choice = input("메뉴를 선택하세요 (1~3): ")

    if choice == "1":
        # 학생 정보 입력 받기
        name = input("이름을 입력하세요: ")
        age = input("나이를 입력하세요: ")
        subject = input("좋아하는 과목을 입력하세요: ")
        score = input("점수를 입력하세요: ")

        # 파일에 저장
        with open("students.txt", "a", encoding="utf-8") as f:
            f.write(f"이름: {name}, 나이: {age}, 과목: {subject}, 점수: {score}\n")

        print(f"{name}님의 정보가 저장되었습니다.")

    elif choice == "2":
        # 파일에서 학생 정보 읽기
        try:
            with open("students.txt", "r", encoding="utf-8") as f:
                data = f.read()
                if data.strip() == "":
                    print("저장된 정보가 없습니다.")
                else:
                    print("\n[전체 학생 정보]")
                    print(data)
        except FileNotFoundError:
            print("아직 저장된 정보가 없습니다. 먼저 정보를 추가해주세요.")

    elif choice == "3":
        print("프로그램을 종료합니다.")
        break

    else:
        print("잘못된 입력입니다. 1, 2, 3 중에서 선택해주세요.")


마무리 퀴즈

  1. 사용자에게 메뉴를 반복적으로 보여주기 위해 어떤 문법을 썼나요? → while 반복문
  2. 정보를 구분해서 저장하려면 어떤 기호가 좋을까요? → 쉼표(,), 콜론(:) 등
  3. 예외 상황 처리(파일이 없을 때)를 위해 어떤 문법을 사용했나요? → try-except

다음 시간 예고

지금까지 만든 프로그램을 기반으로 더 다양한 기능(검색, 삭제, 정렬 등)을 추가해보는 심화 실습이 이어집니다.


TechTinkerer's에서 더 알아보기

구독을 신청하면 최신 게시물을 이메일로 받아볼 수 있습니다.

댓글 남기기

  • The State of Healthcare in Korea: A Path to Normalization

    The Korean healthcare system has been facing significant challenges in recent years. From a crisis point to a path towards normalization, the journey ahead will be crucial for the country’s health sector. In 2022, the healthcare system was at an all-time low, with long waiting times, inadequate medical equipment, and a severe shortage of medical…

  • **Western Countries Express Concern Over Russian Tanker Sinking**

    The recent sinking of a Russian tanker in the Barents Sea has sparked concerns among Western countries over potential implications for global energy markets. The incident raises questions about the security of international shipping lanes and the role of Russia’s military presence in the region. Several reports have emerged indicating that the Russian tanker, which…

  • **Xi Jinping’s Unexpected Gift to South Korea**

    In a surprising move, Chinese President Xi Jinping recently gifted South Korean President Yoon Suk-yup with an electric bicycle. The gesture has been interpreted as a sign of goodwill between the two nations, but it also highlights the complexities of their relationship. The incident took place during a meeting between the two leaders in Seoul,…

  • **South Korean Diplomat Returns to US After 70 Days**

    The United States and South Korea have welcomed back a key diplomat, Kevin Kim, who served as the country’s special representative to the US. Kim’s return comes after a nearly one-year absence from his post, during which time Washington struggled to find a suitable replacement. Kim’s departure in January last year was widely seen as…

  • The Fate of Greenland hangs in the Balance: A Global Power Play

    The fate of Greenland has become a focal point of global politics, with multiple nations vying for control over the strategic island. In recent weeks, several countries have expressed interest in acquiring or partnering with Greenland to further their interests. This article will examine the situation and explore the potential implications for international relations. The…

← 뒤로

응답해 주셔서 감사합니다. ✨

TechTinkerer's에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

계속 읽기

TechTinkerer's에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

계속 읽기