Python Quiz for APCSP
Ethan Zhao
import getpass
# question format, gets user answer
def question_with_response(prompt):
print("Question: " + prompt)
msg = input()
return msg
# lists of questions/answers
prompts=["What command would you use to display text into the terminal?", "What command would you use to ask the user for information?", "What is the keyword used in Python to define a function?", "How would you write a print statement to concatenate a string containing variable A with string 'Hello'? (include print() and use '' instead of \"\"", "How do we add a pre-made library to our code?", "We use _______ to store information for later use.", "Given the code, {variable = 1} what type of variable is this?", "Given the code, {variable = 1.1} what type of variable is this?", "Given the code, {variable = 'Hello'} what type of variable is this?"]
answers=["print", "input", "def", "print('hello' + a)", "import", "variables", "integer", "float", "string"]
correct = 0
questions = len(prompts)
# corrects answers, awards a point if correct
def gradeResponse(response, answer):
global correct
# convert to lowercase so ppl don't yell at me for scoring them as wrong when they went "prinT"
if response.lower() == answer:
print(f"{response} is correct!\nGood job :D")
correct += 1
else:
print(f"{response} is incorrect!\nBetter luck next time :(")
# ask user if they want to proceed, exit if no
print(f"Hello {getpass.getuser()}!")
print(f"You will be asked {str(questions)} questions.")
rsp = question_with_response("Are you ready to take a quiz? [Y/n]")
if rsp.lower() == "y":
print("Lets get started!")
else:
print("Bye :(")
exit()
# cycle through all questions, score the questions
for i in range(0, questions):
rsp = question_with_response(prompts[i])
gradeResponse(rsp, answers[i])
# calculate percentage
percentage=(correct/questions)*100
percentage=round(percentage, 2)
# report score
print(f"You got a total of {correct} out of {questions} ({percentage}%)!")
Code explanation
I import the getpass library that way I can personalize it and say the user name.
The function question_with_response
asks the question and returns the user answer, named msg
.
For every question in the list questions
, I pass the variable msg
into rsp
and send it to the gradeResponse
function, along with the corresponding answer.
gradeResponse
will then check if the answer is correct and award a point to the user if it is.
At the end of the quiz, it will display how many out of the total questions were correct.