循环中Python的无限循环

时间:2012-10-17 01:10:55

标签: python variables loops

我不知道什么是错的。当我在左侧放入x * x而在右侧放入25时,它不起作用。 python shell没有显示错误,但在输入解决方案数量后,没有任何反应。我认为它可能是无限循环,或者在每次运行后都不应用x。请帮忙!这是我的代码:

#getting input information

print
print "This program cannot solve for irrational or repeating numbers. Please round for them in your equation."
print
print "Make the variable in your equation stand for x"
print
startingLimit=int(raw_input("What is the lowest estimate that your variable could possibly be?"))
print
wholeNumber=raw_input("Do you know if your variable will be a whole number or a fraction? Answer: yes/no")
if (wholeNumber== "yes"):
     print
     fraction= raw_input("Is it a decimal/fraction? Answer:yes/no")
     if (fraction=="yes"):
        print
        print "This program will only calculate up to the fourth place to the right of the decimal"
        xfinder=0.0001
    else:
        xfinder=1
else:
    xfinder=0.0001

x=0        
leftEquation=raw_input("Enter your left side of the equation:")
print
rightEquation=raw_input("Enter the right side of the equation:")
print
amountSolutions=raw_input("How many solutions are there to your equation? (up to 20)")



#solving

indivisualCount=0
count=0
x=startingLimit
while (count!=amountSolutions):


    while (count==0):
        ifstuffleft=eval(leftEquation)
        ifstuffright=eval (rightEquation)
        if (ifstuffleft!=ifstuffright):
            x=x+xfinder
        else:
            a=x
            count=count+1

2 个答案:

答案 0 :(得分:2)

  1. 为什么你的内部while (count==0): while循环?只要while (count!=amountSolutions):不等于0,就会导致它卡在无限循环(在count循环中)(因为它永远不会在循环中进入内部)。

  2. 修复后,请注意,如果值彼此相等,则不执行x=x+xfinder。这意味着您将保持相同的值(在这种情况下为-5),直到您满足解决方案的数量。因此,无论值是否相等,您都必须将值增加xfinder

  3. 您永远不会打印解决方案或对其执行任何操作。您可能希望将a=x行替换为print "One solution is", x

  4. 最后,当您发布问题时,您应该努力寻找 minimal 示例。您可以通过对5个变量进行硬编码来替换所有输入代码,例如:

    startingLimit = -10
    xfinder = 1
    leftEquation = "x*x"
    rightEquation = "25"
    amountSolutions = 2
    

    这a)需要23行代码,使您的问题更易于阅读和理解; b)使测试更容易,以便人们可以在不回答六个问题的情况下看到问题并且c)防止回答者不得不猜测你是什么投入startingLimitamountSolutions

答案 1 :(得分:0)

如果为1提供了amountSolutions以外的任何值,则此代码似乎会进入无限循环。

while (count!=amountSolutions):
    while (count==0):

在上面找到一个解决方案时,count = 1因此会跳过内部while循环。