본문 바로가기

개발자/파이썬 Python

파이썬 퀴즈 문제 만들고 정답 확인하는 코드

반응형

 

 

문제를 내면 사용자가 정답을 입력하고 검사하여 결과를 알려주는 코드 두 가지 예제 코드

 

1번과 2번은 크게 다르지 않은데 1번 예제는 question과 답안 문항과 정답을 튜플과 리스트로 만든 경우이고, 2번 예제는 문제를 저장하는 튜플에 정답을 포함시키고, 게임 시작하는 부분, 정답을 체크하는 부분, 결과를 출력하는 부분을 각각 함수로 만들었다. 2번 코드를 추천한다. 두 가지 코드를 비교해 보았다.  2번 예제가 더욱 간결해 보이는 이유는 아마도 함수를 써서 작성했고 코드가 복잡하지 않다.

 

 

1번 예제

# Python quiz game

questions = ("How many elements are in the periodic table?: ",
                       "Which animal lays the largest eggs?: ",
                       "What is the most abundant gas in Earth's atmosphere?: ",
                       "How many bones are in the human body?: ",
                       "Which planet in the solar system is the hottest?: ")

options = (("A. 116", "B. 117", "C. 118", "D. 119"),
                   ("A. Whale", "B. Crocodile", "C. Elephant", "D. Ostrich"),
                   ("A. Nitrogen", "B. Oxygen", "C. Carbon-Dioxide", "D. Hydrogen"),
                   ("A. 206", "B. 207", "C. 208", "D. 209"),
                   ("A. Mercury", "B. Venus", "C. Earth", "D. Mars"))

answers = ("C", "D", "A", "A", "B")
guesses = []
score = 0
question_num = 0

for question in questions:
    print("----------------------")
    print(question)
    for option in options[question_num]:
        print(option)

    guess = input("Enter (A, B, C, D): ").upper()
    guesses.append(guess)
    if guess == answers[question_num]:
        score += 1
        print("CORRECT!")
    else:
        print("INCORRECT!")
        print(f"{answers[question_num]} is the correct answer")
    question_num += 1

print("----------------------")
print("       RESULTS        ")
print("----------------------")

print("answers: ", end="")
for answer in answers:
    print(answer, end=" ")
print()

print("guesses: ", end="")
for guess in guesses:
    print(guess, end=" ")
print()

score = int(score / len(questions) * 100)
print(f"Your score is: {score}%")

 

위 코드를 실행하면 아래와 같다. 전부 틀렸다. ㅎㅎ

 

----------------------
How many elements are in the periodic table?: 
A. 116
B. 117
C. 118
D. 119
Enter (A, B, C, D): a
INCORRECT!
C is the correct answer
----------------------
Which animal lays the largest eggs?: 
A. Whale
B. Crocodile
C. Elephant
D. Ostrich
Enter (A, B, C, D): b
INCORRECT!
D is the correct answer
----------------------
What is the most abundant gas in Earth's atmosphere?: 
A. Nitrogen
B. Oxygen
C. Carbon-Dioxide
D. Hydrogen
Enter (A, B, C, D): c
INCORRECT!
A is the correct answer
----------------------
How many bones are in the human body?: 
A. 206
B. 207
C. 208
D. 209
Enter (A, B, C, D): d
INCORRECT!
A is the correct answer
----------------------
Which planet in the solar system is the hottest?: 
A. Mercury
B. Venus
C. Earth
D. Mars
Enter (A, B, C, D): a
INCORRECT!
B is the correct answer
----------------------
       RESULTS        
----------------------
answers: C D A A B 
guesses: A B C D A 
Your score is: 0%

 

 

2번 예제

 

# ----------------------------
def new_game():
    guesses = []
    correct_guesses = 0
    question_num = 1

    for key in questions:
        print("-------------------")
        print(key)
        for i in options[question_num - 1]:
            print(i)
        guess = input("Enter(A, B, C, or D: ")
        guess = guess.upper()
        guesses.append(guess)

        correct_guesses += check_answer(questions.get(key), guess)
        question_num += 1

    display_score(correct_guesses, guesses)

# ----------------------------
def check_answer(answer, guess):
    if answer == guess:
        print("CORRECT!")
        return 1
    else:
        print("WRONG!")
        return 0


# ----------------------------

def display_score(correct_guesses, guesses):
    print("-------------------------")
    print("RESULT")
    print("-------------------------")
    print("Answers: ", end="")
    for i in questions:
        print(questions.get(i), end=" ")
    print()
    print("Guesses: ", end="")
    for i in guesses:
        print(i, end=" ")
    print()

    score = int((correct_guesses/len(questions))*100)
    print("Your score is: " + str(score) + "%")

# ----------------------------

def play_again():
    response = input("Do you want to play again? (yes or no): ")
    response = response.upper()

    if response == "YES":
        return True
    else:
        return False

# ----------------------------


questions = {
    "Who created Python?: ": "A",
    "What year was python created?: ":"B",
    "Python is tributed to which comedy group?: ":"C",
    "Is the Earth round? ":"A"
}

options = [["A. Guido van Rossum","B. Elon Musk","C. Bill Gates","D. Mark Zuckerburg"],
          ["A. 1989","B. 1991","C. 2000","D. 2016"],
          ["A. Lonely Island","B. Smosh","C. Monty Python","D. SNL"],
          ["A. True","B. False","C. sometimes","D. What's Earth?"]]

new_game()

while play_again():
    new_game()

print("Byeeeeeeee!")

 

아래는 2번 예제를 실행하면 나오는 결과 화면이다.

 

-------------------
Who created Python?: 
A. Guido van Rossum
B. Elon Musk
C. Bill Gates
D. Mark Zuckerburg
Enter(A, B, C, or D: a
CORRECT!
-------------------
What year was python created?: 
A. 1989
B. 1991
C. 2000
D. 2016
Enter(A, B, C, or D: b
CORRECT!
-------------------
Python is tributed to which comedy group?: 
A. Lonely Island
B. Smosh
C. Monty Python
D. SNL
Enter(A, B, C, or D: c
CORRECT!
-------------------
Is the Earth round? 
A. True
B. False
C. sometimes
D. What's Earth?
Enter(A, B, C, or D: d
WRONG!
-------------------------
RESULT
-------------------------
Answers: A B C A 
Guesses: A B C D 
Your score is: 75%
Do you want to play again? (yes or no): no
Byeeeeeeee!

 

 

파이썬 퀴즈 문제 만들고 정답 확인하는 코드

 

 

 

 

 

 

반응형

캐어랩 고객 지원

취업, 창업의 막막함, 외주 관리, 제품 부재!

당신의 고민은 무엇입니까? 현실과 동떨어진 교육, 실패만 반복하는 외주 계약, 아이디어는 있지만 구현할 기술이 없는 막막함.

우리는 알고 있습니다. 문제의 원인은 '명확한 학습, 실전 경험과 신뢰할 수 있는 기술력의 부재'에서 시작됩니다.

이제 고민을 멈추고, 캐어랩을 만나세요!

코딩(펌웨어), 전자부품과 디지털 회로설계, PCB 설계 제작, 고객(시장/수출) 발굴과 마케팅 전략으로 당신을 지원합니다.

제품 설계의 고수는 성공이 만든 게 아니라 실패가 만듭니다. 아이디어를 양산 가능한 제품으로!

귀사의 제품을 만드세요. 교육과 개발 실적으로 신뢰할 수 있는 파트너를 확보하세요.

지난 30년 여정, 캐어랩이 얻은 모든 것을 함께 나누고 싶습니다.

카카오 채널 추가하기

카톡 채팅방에서 무엇이든 물어보세요

귀사가 성공하기까지의 긴 고난의 시간을 캐어랩과 함께 하세요.

캐어랩 온라인 채널 바로가기

캐어랩