This is the code I have so far:
questions = ["What is 1 + 1","What is Batman's real name"]
answer_choices = ["1)1\n2)2\n3)3\n4)4\n5)5\n:","1)Peter Parker\n2)Tony Stark\n3)Bruce Wayne\n4)Thomas Wayne\n5)Clark Kent\n:"]
correct_choices = ["2","3",]
answers = ["1 + 1 is 2","Bruce Wayne is Batman"]
score = 0
answer_choices = [c.split()[:3] for c in answer_choices]
for question, choices, correct_choice, answer in zip(questions,answer_choices, correct_choices, answers):
print(question)
user_answer = str(input(choices))
if user_answer in correct_choice:
print("Correct")
score += 1
else:
print("Incorrect", answer)
print(score, "out of", len(questions), "that is", float(score /len(questions)) * 100, "%")
My code runs but the answer_choices (so the question options) don't display on a new line for each list element. How can I do this? An explanation would also be nice
You should get rid of this line in order for your code to work:
answer_choices = [c.split()[:3] for c in answer_choices
Notice that you don't have to split answer_choices
since you don't treat the answers of each question as an array.
Moreover, you have more bugs in your code, like the scoring at the end. Here's a formatted and fixed version of your code:
questions = [
"What is 1 + 1?",
"What is Batman's real name?"]
answer_choices = [
"1) 1\n2) 2\n3) 3\n4) 4\n5) 5\n\nYour answer: ",
"1) Peter Parker\n2) Tony Stark\n3) Bruce Wayne\n4) Thomas Wayne\n5) Clark Kent\n\nYour answer: "]
correct_choices = ["2","3",]
answers = [
"1 + 1 is 2",
"Bruce Wayne is Batman"]
score = 0
for question, choices, correct_choice, answer in zip(
questions,answer_choices, correct_choices, answers):
print(question)
user_answer = str(input(choices))
if user_answer in correct_choice:
print("Correct!\n")
score += 1
else:
print("Incorrect! " + answer + "\n")
print score, "out of", len(questions), "that is", int(float(score)/len(questions)*100), "%"
If you remove/comment the line
answer_choices = [c.split()[:3] for c in answer_choices]
you'll get the output as you expect.
Since answer_choices is already a String array, in for loop you are accessing each array element of answer_choices. Also, since each string in answer_choices are in the format you need them to appear, you don't need to split.
just remove
answer_choices = [c.split()[:3] for c in answer_choices]
it give your expected output
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.