Python程序调试:无限循环

发布于 2024-10-23 21:04:56 字数 6546 浏览 1 评论 0原文

背景: 在我的计算机科学课上,我们被要求创建一个程序来帮助小学生学习基础数学。
他们会选择他们想要学习的运算(加法、减法、乘法或除法),或者选择随机,随机选择这些运算之一。
一旦选择了某个操作,就会询问用户一个问题,然后输入答案,如果正确,程序会询问另一个问题,总共最多 4 个问题,然后程序会返回到菜单。
如果答案不正确,则要求用户重新输入答案,最多3次,如果答案仍然不正确,则会显示正确答案,然后会询问另一个问题(如果未达到4个问题的配额) )或如果没有其他问题则返回菜单。

问题: 我已经写好了所有内容,当我在 IDLE 中运行程序时,一切似乎都正常工作,但是在由于某种原因选择了一个操作后,程序陷入无限循环,并且在询问 4 个问题后不会返回到菜单。
我首先使用 for 循环来满足 4 个问题的配额,但这不起作用,所以然后我尝试了一个 while 循环,它读取 while x<4: etc etc,将 x 定义为 x=0 之前while 循环,然后在函数末尾添加 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()`

提前感谢您提供的任何帮助!

Background:
for my computer science class, we were asked to create a program that would help elementary school children learn basic math.
They would select which operation they would like to learn (addition, subtraction, multiplication, or division), or choose random which would choose one of these operations at random.
Once an operation is selected, the user will be asked a question and then to input the answer, if correct the program would ask another question, up to 4 questions total, and then the program would return to the menu.
If the answer is incorrect, it asks the user to input the answer again, up to three times, if the answer is still incorrect, the correct answer would be displayed, then another question would be asked (if the 4 question quota was not met) or return to the menu if there are no other questions.

The Problem:
I have everything written out, and when I run the program in IDLE everything appears to be working, but after an operation is selected for some reason the program is stuck on an infinite loop and wont return to the menu after 4 questions has been asked.
I first used a for loop to meet the 4 question quota and that did not work, so then I tried a while loop which reads while x<4: etc etc, defining x as x=0 before the while loop and then at the end of the function adding x=x+1.

again from reading the code, it appears like it should work for each function, but after running it i'm still stuck in an infinite loop.

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

Thank you in advance for any assistance that anyone here can provide!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

银河中√捞星星 2024-10-30 21:04:56

您需要将 raw_input 放入 while 循环中。

将 main 更改为:

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() 。你可以让函数返回。虽然这与你的错误无关。

You need to put the raw_input within the while loop.

Change main to this:

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

The issue here is that raw_input was called once, before the while loop. However, it was never called again. Instead the loop would continue on, but it would continue to use the same selection value it retrieved in the first (and only) call to raw_input.

Also, you don't need quit() at the end of your main function. You can just let the function return. Although that has nothing to do with your bug.

美人骨 2024-10-30 21:04:56

这将产生基于随机数和运算的问题。

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

This will generate problems based on random numbers and operations.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文