J'ai développé un test et je veux le faire pour que l'utilisateur puisse entrer ses propres réponses au test avant que le test ne démarre réellement. Voici ce que j'ai jusqu'à présent. Serait-il préférable d'utiliser un dictionnaire au lieu de faire des entrées brutes plusieurs fois ou existe-t-il un moyen de demander à l'utilisateur ses réponses sans le faire. Merci!

ready = raw_input("Are you ready to do the test?(Please enter YES/NO) ")

while ready.lower() != "yes":
    ready = raw_input("Are you ready to do the test?(Please enter YES/NO) ")

if ready.lower() == "yes":
    print "Excelent! The test will start in any second."
if ready.lower() == "no":
    print "Okay, tell me when you're ready. "
elif ready.lower() != "yes" and "no":
    print "It okay if your're not sure. The test can start in any time you want. "

count = 0


if ready.lower() == "yes":
    question1 = raw_input("\nQuestion 1\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question1.lower() == "b":
    print "Correct"
    count = count + 1
elif question1.lower() != "b":
    print "Wrong"

question2 = raw_input("\nQuestion 2\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question2.lower() == "d":
    print "Correct"
    count = count + 1
elif question2.lower() != "d":
    print "Wrong"

question3 = raw_input("\nQuestion 3\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
    if question3.lower() == "a":
    print "Correct"
    count = count + 1
elif question3.lower() != "a":
    print "Wrong"

question4 = raw_input("\nQuestion 4\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question4.lower() == "a":
    print "Correct"
    count = count + 1
elif question4.lower() != "a":
    print "Wrong"

question5 = raw_input("\nQuestion 5\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question5.lower() == "c":
    print "Correct"
    count = count + 1
elif question5.lower() != "c":
    print "Wrong"

question6 = raw_input("\nQuestion 6\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question6.lower() == "a":
    print "Correct"
    count = count + 1
elif question6.lower() != "a":
    print "Wrong"

question7 = raw_input("\nQuestion 7\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question7.lower() == "b":
    print "Correct"
    count = count + 1
elif question7.lower() != "b":
    print "Wrong"

question8 = raw_input("\nQuestion 8\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question8.lower() == "a":
    print "Correct"
    count = count + 1
elif question8.lower() != "a":
    print "Wrong"

question9 = raw_input("\nQuestion 9\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question9.lower() == "c":
    print "Correct"
    count = count + 1
elif question9.lower() != "c":
    print "Wrong"

question10 = raw_input("\nQuestion 10\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question10.lower() == "d":
    print "Correct"
    count = count + 1
elif question10.lower() != "d":
    print "Wrong"

question11 = raw_input("\nQuestion 11\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question11.lower() == "b":
    print "Correct"
    count = count + 1
elif question11.lower() != "b":
    print "Wrong"

question12 = raw_input("\nQuestion 12\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question12.lower() == "c":
    print "Correct"
    count = count + 1
elif question12.lower() != "c":
    print "Wrong"

question13 = raw_input("\nQuestion 13\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question13.lower() == "d":
    print "Correct"
    count = count + 1
elif question13.lower() != "d":
    print "Wrong"

question14 = raw_input("\nQuestion 14\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question14.lower() == "a":
    print "Correct"
    count = count + 1
elif question14.lower() != "a":
    print "Wrong"

question15 = raw_input("\nQuestion 15\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question15.lower() == "a":
    print "Correct"
    count = count + 1
elif question15.lower() != "a":
    print "Wrong"

question16 = raw_input("\nQuestion 16\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question16.lower() == "c":
    print "Correct"
    count = count + 1
elif question16.lower() != "c":
    print "Wrong"

question17 = raw_input("\nQuestion 17\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question17.lower() == "c":
    print "Correct"
    count = count + 1
elif question17.lower() != "c":
    print "Wrong"

question18 = raw_input("\nQuestion 18\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question18.lower() == "b":
    print "Correct"
    count = count + 1
elif question18.lower() != "b":
    print "Wrong"

question19 = raw_input("\nQuestion 19\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question19.lower() == "d":
    print "Correct"
    count = count + 1
elif question19.lower() != "d":
    print "Wrong"

question20 = raw_input("\nQuestion 20\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ")
if question20.lower() == "a":
    print "Correct"
    count = count + 1
elif question20.lower() != "a":
    print "Wrong"

print "\n|Congratulation!,", "You have completed the test."
print "|Here's your result."
print "|Total score: " + str(count) + "/20"
division = float(count)/float(20)
multiply = float(division*100)
result = round(multiply)
print "|Total percentage is", int(result), "%"

if result >= 75:
    print ("|Congratulations, you have passed!")

elif result <= 70:
    print ("|Sorry, you have failed.\n|You should study more.")

mis à jour : merci d'avoir récupéré la partie boucle. Maintenant, j'ai juste besoin de savoir comment je peux également permettre à l'utilisateur d'entrer ses propres réponses au test. Pour clarifier, j'entends par là permettre à l'utilisateur d'entrer sa propre clé de réponse au test, puis de commencer le test.

answers = ["b", "d", "a", "a", "c", "a", "b", "a", "c", "d", "b", "c", "d", "a", "a", "c", "c", "b", "d", "a"]

count = 0
for i in range(20):
    answer = raw_input("\nQuestion " + str(i+1) + "\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ");
    if answer.lower() == answers[i]:
        print "Correct"
        count = count + 1
    else:
        print "Wrong"
1
Andrew 3 nov. 2014 à 02:58

3 réponses

Meilleure réponse

Les boucles sont juste créées pour éviter ce codage. --blague.

Vous pouvez créer une liste de réponses où les bons choix sont conservés. Ensuite, vous pouvez parcourir les questions avec une boucle for. Voici un exemple:

answers = ["b", "d", "a", "a", "c", "a"]

count = 0
for i in range(len(answers)):
    answer = raw_input("\nQuestion " + str(i+1) + "\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ");
    if answer.lower() == answers[i]:
        print "Correct"
        count = count + 1
    else:
        print "Wrong"
0
Batuhan Tasdoven 3 nov. 2014 à 00:04

Vous devez utiliser une classe . Voici une maquette rapide basée sur ce que vous avez jusqu'à présent, elle est plus flexible et réutilisable aussi. Pensez que vous avez différents ensembles de questions pour différentes notes, ce n'est pas complet, mais cela vous aidera à démarrer.

J'ai également mis quelques commentaires et j'espère que le code va de soi:

class Questions:
    def __init__(self, title='', answers=[]):
        # title can then be changed to whatever you like (A,B,C,D,E,F... etc.)
        self.title = title
        # answers will be a python list, just like you have now
        self.answers = answers
        # we use a dictionary to store question N and its correct answer
        self.questions = {}
        # no of questions answered correctly
        self.count = 0
        # a boolean flag whether the test has been completed
        self.completed = False
        # check if answers are set, then loop through the list and set the key/value pair
        if self.answers:
            for i, answer in enumerate(self.answers):
                self.questions['Question ' + str(i+1)] = answer

    def start(self):
        if not self.answers:
            print "No question and answer set yet"
            return
        # you only need a YES answer, so set a while loop to break only on YES
        while raw_input('Are you ready to do the test? (Please enter YES/NO) ').lower() != 'yes':
            pass
        # reset the count in case people break in the middle of the questions
        self.count = 0
        # just iterate the list, and get the key/value pair as a question
        for i, answer in enumerate(self.answers):
            question = 'Question ' + str(i+1)
            ans = raw_input(question +'\n' + self.title)
            if ans.lower() == self.questions[question]:
                print "Correct"
                self.count += 1
            # quite obvious, if not Correct, that's Wrong
            else:
                print "Wrong"
        # once all questions answered, set completed flag as True
        self.completed = True
        # now go to get_result to print all stats you want
        return self.get_result()

    def get_result(self):
        # to check if all questions are actually completed
        if not self.completed:
            print "You still haven't completed the test yet"
            return
        print "\n|Congratulation!,", "You have completed the test."
        print "|Here's your result."
        print "|Total score: " + str(self.count) + "/20"
        division = float(self.count)/float(20)
        multiply = float(division*100)
        result = round(multiply)
        print "|Total percentage is", int(result), "%"
        if result <= 70:
            print ("|Sorry, you have failed.\n|You should study more.")
        # well again, if result is not <=70, it will be above.
        else:
            print ("|Congratulations, you have passed!")

Usage:

# set the title so do not repeat yourself on each question asked
# and the answers will be a list of the Correct answer, you get the idea
myquestions = Questions(title='What is your answer?\nPlease enter A, B, C or D: ', answers=['b','d','a','c','a','b','a','c','d','b','c','d','a','c','c','b','d','a'])

# After you instantiated your class, the __init__ is called, and so the questions dictionary is created automatically
 myquestions.questions
{'Question 1': 'b',
 'Question 10': 'b',
 'Question 11': 'c',
 'Question 12': 'd',
 'Question 13': 'a',
 'Question 14': 'c',
 'Question 15': 'c',
 'Question 16': 'b',
 'Question 17': 'd',
 'Question 18': 'a',
 'Question 2': 'd',
 'Question 3': 'a',
 'Question 4': 'c',
 'Question 5': 'a',
 'Question 6': 'b',
 'Question 7': 'a',
 'Question 8': 'c',
 'Question 9': 'd'}

Pour commencer votre test, appelez myquestions.start()

myquestions.start()
Are you ready to do the test? (Please enter YES/NO) yes

Question 1
What is your answer?

A
B
C
D
Please enter A, B, C or D: b
Correct

...

Question 18
What is your answer?

A
B
C
D
Please enter A, B, C or D: s
Wrong

|Congratulation!, You have completed the test.
|Here's your result.
|Total score: 1/20
|Total percentage is 5 %
|Sorry, you have failed.
|You should study more.

À la fin de toutes les questions, le get_result sera appelé et imprimera vos statistiques.

Mon code n'est pas vraiment optimisé, mais cela devrait vraiment vous aider à comprendre comment utiliser la classe pour résoudre les problèmes similaires que vous rencontrez à l'avenir.

0
Anzel 3 nov. 2014 à 01:14

Vous pouvez toujours utiliser des listes 2D avec la boucle for, l'utilisation de Dict ne maintiendra pas l'ordre des questions, sinon vous voudrez peut-être utiliser Dict ordonné ...

Dans la liste 2d, vous pouvez écrire la question ainsi que ses réponses

questions = [["\nQuestion {0}\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ","b"],
             ["\nQuestion {0}\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ","d"],
             ["\nQuestion {0}\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ","a"],
             ["\nQuestion {0}\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ","c"],
             ["\nQuestion {0}\nWhat is your answer?\n \nA\nB\nC\nD\n\nPlease enter A, B, C or D: ","d"]]

count=0

for n,i in enumerate(questions):
    quest = raw_input(i[0].format(n))
    if quest.lower() == i[1]:
        print "Correct"
        count = count + 1
    elif quest.lower() != i[1]:
        print "Wrong"
0
blackwind 3 nov. 2014 à 00:16