더보기
def load_quiz(file_path):
questions = []
with open(file_path, "r", encoding="utf-8") as file:
content = (
file.read()
.strip()
.split(
"\n--------------------------------------------------------------------------------------------\n"
)
)
for item in content:
if "(답)" in item:
question, answer = item.split("(답)", 1)
question = question.strip()
answer = answer.strip()
question = question.replace(
"\n--------------------------------------------------------------------------------------------\n",
"",
).strip()
answer = answer.replace(
"\n--------------------------------------------------------------------------------------------\n",
"",
).strip()
questions.append((question, answer))
else:
print("잘못된 형식의 문제를 발견했습니다:", item)
return questions
def start_quiz(quiz_data):
score = 0
total_questions = len(quiz_data)
current_idx = 0
print(
f"--------------------------------------------------------------------------------------------"
)
print(f"출처:온계절, https://m.blog.naver.com/stereok2")
print(f"제작:solze, https://thodi-lab.tistory.com/")
print(
f"그만하려면 'exit' 입력, 건너뛰려면 'next' 입력, 이전 문제로 가려면 'plz' 입력, 문제 번호로 이동하려면 'go [번호]' 입력\n"
)
while current_idx < total_questions:
question, correct_answer = quiz_data[current_idx]
print(f"문제 {current_idx + 1}/{total_questions}: {question}")
user_answer = input("답을 입력하세요: ").strip()
if user_answer.lower() == "exit":
print("퀴즈를 종료합니다.")
break
if user_answer.lower() == "next":
print("문제를 건너뜁니다.\n")
current_idx += 1
continue
if user_answer.lower() == "plz":
if current_idx > 0:
current_idx -= 1
print("이전 문제로 돌아갑니다.\n")
continue
else:
print("첫 번째 문제입니다. 이전 문제가 없습니다.\n")
continue
if user_answer.lower().startswith("go "):
try:
target_idx = int(user_answer.split()[1]) - 1
if 0 <= target_idx < total_questions:
current_idx = target_idx
print(f"문제 {current_idx + 1}/{total_questions}로 이동합니다.\n")
continue
else:
print("잘못된 문제 번호입니다.\n")
except (ValueError, IndexError):
print("잘못된 입력입니다. 문제 번호를 올바르게 입력하세요.\n")
continue
print(f"정답은: {correct_answer}\n")
current_idx += 1
print(f"퀴즈 종료! 총 {total_questions}문제를 모두 확인했습니다.")
print(
f"정보보안기사 합격을 기원합니다 ! 자료 제공에 도움을 주신 온계절님께 감사드립니다."
)
print(
f"--------------------------------------------------------------------------------------------"
)
if __name__ == "__main__":
print("파일 경로를 입력하세요 (예: C:/Users/사용자명/Desktop/파일명.txt):")
quiz_file = input().strip()
try:
quiz_data = load_quiz(quiz_file)
start_quiz(quiz_data)
except FileNotFoundError:
print("파일을 찾을 수 없습니다. 경로를 다시 확인해주세요.")
1. 내가 고려해야 했던 것들
- 퀴즈에 쓰일 문제/답 데이터가 계속 업데이트되어도 코드 수정은 없어야 한다.
- 1번부터 순서대로 풀기만 하는 게 아니라 자유롭게 활용할 수 있어야 한다.
2. 제작 방법
- 단답형 퀴즈 프로그램 만들면서 생긴 근자감과 '서술형도 해볼만한데?'라는 마음가짐으로 시작
- ChatGPT를 통한 코딩 *gpt야 "해줘"..
3. 아쉬운 점
(1) 현재 코드는 퀴즈 형식이 아닌 정답을 보여주기만 하고 있음
-> 특정 키워드 포함 시 정답과 근접하다는 것을 알려줄 수 있다면 좋았을텐데.. 고민하다가 어려워서 포기 😭
(2) 파일 예외 처리
-> FileNotFoundError 외에도 PermissionError나 일반적인 Exception을 처리해야 함
try:
quiz_data = load_quiz(quiz_file)
if not quiz_data:
print("퀴즈 파일이 비어 있거나 올바른 형식이 아닙니다.")
else:
start_quiz(quiz_data)
except FileNotFoundError:
print("파일을 찾을 수 없습니다. 경로를 다시 확인해주세요.")
except PermissionError:
print("파일을 열 권한이 없습니다. 관리자 권한으로 실행하거나 다른 경로를 시도하세요.")
except Exception as e:
print(f"오류 발생: {e}")
(3) 구분선 처리
print(f"--------------------------------------------------------------------------------------------")
보다는 아래 코드가 더 가독성이 있으려나..?
print("\n" + "-" * 92)
'Study > Python' 카테고리의 다른 글
[Python] 'GPT에게 코딩을 맡기기 위한 코딩 강의' 리뷰 (0) | 2025.03.20 |
---|---|
[Python] 코드 리뷰 : 데이터 가공 및 정렬 자동화 프로그램 (5) | 2025.02.05 |
[Python] 코드 리뷰 : 정보보안기사 실기 단답형 퀴즈 프로그램 (0) | 2025.02.05 |
[Python] 숫자 계산하기 (3) | 2024.12.25 |
[Python] flask와 웹 스크래퍼와 사이트 제작 (8) | 2024.11.12 |