Home > Back-end >  How would I use functions to make my code not as repetitive and more efficient?
How would I use functions to make my code not as repetitive and more efficient?

Time:07-31

I've essentially written this if statement 9 times in a quiz game project for the 9 questions and answers I need. How would I define a function to potentially condense these if statements?

questionOne = input(listQuestions[0])
questionOneCasing = questionOne.title()
if questionOneCasing == "Quentin Tarantino":
  score = score   1
  print("Correct, your score is "   str(int(score))   "!")
else:

 print("Unfortanetely this is incorrect! Your score is "   str(int(score))   ".")

CodePudding user response:

Use a list of dictionaries to separate logic from data. For example:

questions = [{"question": "Question 1... ?", "answer": "answer 1"},
             {"question": "Question 2... ?", "answer": "answer 2"},
             {"question": "Question 3... ?", "answer": "answer 3"},
             {"question": "Question 4... ?", "answer": "answer 4"},
] #todo rename fields if wanted

score = 0
for question in questions:
    given_answer = input(question["question"])
    if given_answer == question["answer"]: #todo refine check
        score  = 1
    else:
        print("wrong answer")
    print("your score is {}".format(score))

CodePudding user response:

Start off with questions in this format:

# Replace with actual questions and answers - add as many as you need
questions = [
    ('question 1', 'answer 1'),
    ('question 2', 'answer 2'),
    ('question 3', 'answer 3')
]

Then, using loops:

score = 0
for q, a in questions:
    ans = input(q)
    if ans.lower() == a.lower(): # or whatever check you want
        score  = 1
        print('Correct!\n')
    else:
        print('Wrong!\n')
print(f'You got {score} out of {len(questions)}!')

Or, using a recursive function:

def check(qs, i=0):
    if i >= len(qs):
        return 0
    q, a = qs[i]
    ans = input(q)
    return (ans.lower() == a.lower())   check(qs, i 1)

score = check(questions)
print(f'You got {score} out of {len(questions)}')

CodePudding user response:

You could also do something with a class like:

score = 0

class quizQuestion(self, question, answer)
    self.question
    self.answer
  def answerCorrectly(self)
    print("Correct!")
    score  = 1
  def answerIncorrect(self)
    print("incorrect")
    score -= 1

quizQuestion("Who is luke's father?", "darth vader")

#So basically now all you would have to do is:

quizQuestionAnswer = input

if quizQuestionAnswer == answer:
    answerCorrect

Its something along those lines but you would have to polish it

  • Related