While在if语句中循环?

时间:2019-01-08 20:05:09

标签: python python-3.x function if-statement while-loop

这里是初学者程序员:))我正在做一个学校项目,任务是在一个文件中找到五个函数的根。

在我的功能之一中,有两个根,而我的代码只能找到一个。似乎第二个while循环被忽略了。我试图仅将此代码放在单独的文件中,并且可以正常工作-但与其他文件一起工作将不起作用...

只需问是否有奇怪的东西;)

def b(x: float):
    return -x**2+x+6

def bgraf():
    xlim(a1, b1)
    ylim(-15, 25)
    x = linspace(-5, 10, 1000)
    y = b(x)
    plot(x, y, 'r')
    return

funksjoner = [0, 1, 2, 3, 4]

while response not in funksjoner:
    i = int(input("choose a function from 0 to 4"))
    response = i
    if response in funksjoner:
        print("you chose function ", int(funksjoner[i]))

a1 = float(input())
b1 = float(input())
z = a1
y = b1
m = a1
n = b1
NP = True

if int(funksjoner[i]) == funksjoner[1]:
    while abs(y-z) > 1e-10:
        null1 = (z+y)/2
        if b(z)*b(null1)>0 and b(y)*b(null1)>0: 
            NP = False
            print('No roots in this interval')
            bgraf()
            break
        elif b(null1) == 0:
            break
        elif b(z)*b(null1)>0:
            z = null1
        else :
            y = null1
    while abs(n-m) > 1e-10:
        null1_2 = (m+n)/2
        if b(m)*b(null1_2)>0 and b(n)*b(null1_2)>0: 
            NP = False
            print('No roots in this interval')
            bgraf()
            break
        elif b(null1_2) == 0:
            break
        elif b(m)*b(null1_2)>0:
            m = null1_2
        else :
            n = null1_2
    if NP :
        print('we have a root when x =', round(((z+y)/2), 1))
        if null1 != null1_2:
            print('and when x =', round(((m+n)/2), 1))
        bgraf()
        scatter(null1, 0)
        if null1 != null1_2:
            scatter(null1_2, 0)

看起来python忽略了我放在if语句下的第二个while循环。我还有其他办法吗?

感谢您的关注!

1 个答案:

答案 0 :(得分:0)

需要考虑的几件事:

  1. 您希望通过以下代码行实现什么: 如果int(funksjoner [i])== funksjoner [1] 您可以简单地检查 如果i == 1

  2. 我看不到第一个和第二个while循环之间的任何区别。 z = m = a1 y = n = a2 那么这两者之间应该有什么区别?

  3. 通常,由于变量的命名,代码难以阅读,请尝试使用使您印象深刻的变量。

  4. 要获得更好的印象,请使用调试,或者,如果您不熟悉调试,请在代码中添加打印语句,以更好地了解执行时间何时存储在变量中。以及执行了哪些语句以及跳过/未达到的语句

当您向我们提供有关您的代码的更详细的信息(例如,可以添加注释以解释您的代码)时,如果您有更详细的问题,我们会为您提供更好的支持

相关问题