개발자/파이썬 Python

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

지구빵집 2022. 12. 27. 09:57
반응형

 

 

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

 

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!

 

 

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

 

 

 

 

 

 

반응형