簡體   English   中英

Python程序調試:無限循環

[英]Python program debugging: infinite loop

背景:在我的計算機科學課程中,我們被要求創建一個程序來幫助小學生學習基礎數學。
他們將選擇他們想學習的操作(加法,減法,乘法或除法),或者選擇隨機,而隨機選擇這些操作之一。
一旦選擇了一項操作,將向用戶詢問一個問題,然后輸入答案,如果正確,程序將詢問另一個問題,總共最多四個問題,然后程序將返回菜單。
如果答案不正確,它會要求用戶再次輸入答案,最多3次,如果答案仍然不正確,則將顯示正確答案,然后將詢問另一個問題(如果未滿足4個問題的配額),如果沒有其他問題,請返回菜單。

問題:我已經把所有內容寫完了,當我在IDLE中運行程序時,一切似乎都可以正常工作,但是由於某種原因選擇了某個操作之后,程序陷入了無限循環,並且在出現4個問題之后就不會返回菜單被問到。
我首先使用了一個for循環來滿足4個問題的配額,但是這沒有用,因此我嘗試了一個while循環,該循環讀取while x<4: etc etc ,在while循環之前然后在結尾將x定義為x = 0加x=x+1的函數。

再次從閱讀代碼來看,它似乎應該適用於每個功能,但是運行它之后,我仍然陷入無限循環。

這是代碼:

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()`

預先感謝您在這里提供的任何幫助!

您需要將raw_input放入while循環中。

更改為:

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."

這里的問題是raw_input在while循環之前被調用了一次。 但是,它再也沒有被調用過。 取而代之的是,循環將繼續進行,但是它將繼續使用在第一次(也是唯一一次)對raw_input調用中檢索到的selection值。

另外,您不需要在main函數的末尾使用quit() 您可以讓函數返回。 盡管這與您的錯誤無關。

這將基於隨機數和運算產生問題。

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM