Question

Arrière-plan: pour ma classe de la science informatique, on nous a demandé de créer un programme qui aiderait les enfants de l'école élémentaire à apprendre les mathématiques de base.
Ils choisiraient quelle opération ils aimeraient apprendre (addition, soustraction, multiplication ou division), ou choisir au hasard qui choisirait une de ces opérations au hasard.
Une fois qu'une opération est sélectionnée, l'utilisateur sera posé une question, puis d'entrer la réponse, si elle est correcte le programme se poser une autre question, jusqu'à 4 questions au total, puis le programme retournerait au menu.
Si la réponse est incorrecte, il demande à l'utilisateur de saisir la réponse à nouveau, jusqu'à trois fois, si la réponse est toujours incorrecte, le serait affiché bonne réponse, puis une autre question serait demandé (si le quota de 4 question n'a pas été atteint ) ou revenir au menu s'il n'y a pas d'autres questions.

Le problème: J'ai tout écrit, et quand je lance le programme dans tout IDLE semble fonctionner, mais après une opération est sélectionnée pour une raison quelconque le programme est bloqué sur une boucle infinie et le retour wont au menu après 4 questions a été posée.
J'ai d'abord utilisé une boucle pour atteindre le quota de 4 questions et qui n'a pas fonctionné, alors j'ai essayé un certain temps boucle qui lit while x<4: etc etc, définissant x x = 0 avant la boucle while, puis à la fin de la fonction ajoutant x=x+1.

à nouveau à la lecture du code, il semble que cela devrait fonctionner pour chaque fonction, mais après l'exécution de ce que je suis encore coincé dans une boucle infinie.

Heres le code:

def show_instructions():
    """
    Displays a greeting to the user and provides instructions on how to use the
    program.        [PURPOSE]
    """
    print " "
    print "-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-"
    print "                             Math Mania"
    print " "
    print "Welcome to Math Mania! This program is designed to help you learn basic"
    print "math skills in addition, subtraction, multiplication, and division."
    print "-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-"
    print " "
    print "To learn a skill, type the first letter of that skill."
    print " "
    print "a for addition"
    print "s for subtraction"
    print "m for multiplication"
    print "d for division"
    print "r for random"
    print "q to quit"
    print " "


def add():
    """
    generates display two random numbers and sums them, then prompts the user
    to input the correct sum, if the input is incorrect, it prompts the user
    to try again.
    [PURPOSE]
    """

    x=0
    while x<4:
        num1 = random.randint(1,20)
        num2 = random.randint(1,20)
        print num1, "+", num2, '= ?'
        answer = input ('Enter your answer: ')
        count1=0
        while answer != num1+num2 and count1<3:
            count1=count1 +1
            print 'Incorrect, please try again.'
            print
            print num1, '+', num2, '= ?'
            answer = input ('Enter your answer: ')
        if count1==3:
            print "Sorry, that's incorrect."
            print "The correct answer is ",num1+num2 
        else:
            print "That's correct!"
        print
        x=x+1



def sub():
    """
    generates and displays two random numbers and subtracts the smaller of the
    two from the larger one. It then prompts the user to input the correct
    answer, if the input is incorrect, it prompts the user to try again.
    [PURPOSE]
    """
    x=0
    while x<4:
        num1 = random.randint(1,20)
        num2 = random.randint(1,20)
        if num1>num2:
            print num1, "-", num2, '= ?'
            answer = input('Enter your answer: ')
            count1=0
            while answer != num1 - num2 and count1<3:
                count1=count1+1
                print 'Incorrect, please try again.'
                print
                print num1, "-", num2, '= ?'
                answer = input ('Enter your answer: ')
            if count1==3:
                print "Sorry, that's incorrect."
                print "The correct answer is ",num1-num2
            else:
                print "That's correct!"
            print
            x=x+1
        else:
            print num2, "-", num1, '= ?'
            answer = input ('Enter your answer')
            count1=0
            while answer!= num2-num1 and count1<3:
                count1=count1+1
                print 'Incorrect, please try again.'
                print
                print num2, "-", num1, '= ?'
                answer = input ('Enter your answer: ')
            if count1==3:
                print "Sorry, that's incorrect."
                print "The correct answer is ",num2-num1
            else:
                print 'Thats correct!'
            print
            x=x+1

def mult():
    """
    generates and displays two random numbers and finds the product of the two.
    It then prompts the user to input the correct product of the two numbers, if
    the input is incorrect, it prompts the user to try again.
    [PURPOSE]
    """
    x=0
    while x<4:
        num1 = random.randint(1,20)
        num2 = random.randint(1,20)
        print num1, "x", num2, '= ?'
        answer = input ('Enter your answer: ')
        count1=0
        while answer != num1*num2 and count1<3:
            count1=count1+1
            print 'Incorrect, please try again.'
            print
            print num1, 'x', num2, '= ?'
            answer = input ('Enter your answer: ')
        if count1==3:
            print "Sorry, that's incorrect."
            print "The correct answer is ", num1*num2
        else:
            print "That's correct!"
        print
        x=x+1


def div():
    """
    generates and displays the quotient of two numbers, and then prompts the
    user to input the correct answer, if the input is incorrect, it then prompts
    the user to try again.
    [PURPOSE]
    """

    x=0
    while x<4:
        num1 = random.randint(1,20)
        num2 = random.randint(1,20)

        while (num1%num2!=0):
            num2 = random.randint(1,20)
            num1 = random.randint(1,20)
        print num1, "/", num2, '= ?'
        answer = input ('Enter your answer: ')


        count1=0
        while answer != num1/num2 and count1<3:
            count1=count1 +1
            print 'Incorrect, please try again.'
            print num1, '/', num2, '= ?'
            answer = input ('enter your answer:')
        if count1==3:
            print "Sorry, that's incorrect."
            print "The correct answer is ",num1/num2 
        else:
            print "That's correct!"
        print
        x=x+1
def rand():
    """
    picks a arithmetic function at random for the user to to try
    [PURPOSE]
    """
    num=random.randint(1,4)
    if num==1:
        add()
    if num==2:
        sub()
    if num==3:
        mult()
    if num==4:
        div()

def main():
    """
    main function that brings it all together
    [PURPOSE]
    """
    show_instructions()
    selection = raw_input ('Please select the skill you want to learn: ')
    while selection != "q":
        if selection == "a":
            add()
        elif selection == "s":
            sub()
        elif selection == "m":
            mult()
        elif selection == "d":
            div()
        elif selection == "r":
            rand()
    print "The program will now quit."
    quit()
main()`

Merci d'avance pour toute aide que quelqu'un ici peut fournir!

Était-ce utile?

La solution

Vous devez mettre le raw_input dans le while.

Le principal changement à ceci:

def main():
    """
    main function that brings it all together
    [PURPOSE]
    """
    show_instructions()
    selection = None
    while selection != "q":
        selection = raw_input ('Please select the skill you want to learn: ')
        if selection == "a":
            add()
        elif selection == "s":
            sub()
        elif selection == "m":
            mult()
        elif selection == "d":
            div()
        elif selection == "r":
            rand()
    print "The program will now quit."

Le problème ici est que raw_input a été appelé une fois, avant la boucle while. Cependant, il n'a jamais été appelé à nouveau. Au lieu de cela la boucle continuerait, mais il continuerait à utiliser la même valeur selection il récupéré dans le premier (et seul) appel à raw_input.

En outre, vous n'avez pas besoin quit() à la fin de votre fonction main. Vous pouvez laisser le retour de la fonction. Bien que cela n'a rien à voir avec votre bug.

Autres conseils

Cela va générer des problèmes en fonction des nombres aléatoires et des opérations.

from string import lower
from operator import add, sub, mul
from random import randint, choice

ops = { '+': add, '-': sub, '*': mul}
MAXTRIES = 2

def doprob():
    op = choice('+-*')
    nums = [randint(1,10), randint(1,10)]
    nums.sort();nums.reverse()
    ans = apply(ops[op], nums)
    pr = '%d %s %d = ' % (nums[0], op, nums[1])
    oops = 0
    while True:
        try:
            if int(raw_input(pr)) == ans:
                print 'correct'
                break
            if oops == MAXTRIES:
                print 'answer\n%s%d'%(pr, ans)
            else:
                print 'incorrect... try again'
                oops = oops + 1
        except (KeyboardInterrupt, EOFError, ValueError):
            print 'invalid input... try again'

def main():
    while True:
        doprob()
        try:
            opt = lower(raw_input('Again? ' ))
        except (KeyboardInterrupt, EOFError):
            print ; break
        if opt and opt[0] == 'n':
            break

if __name__ == '__main__':
    main()

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top