Python二次循环

时间:2017-01-22 06:37:25

标签: python loops

我很难理解python中的循环。我想创建一个循环,不断提示用户输入a,b,c,然后计算答案,显示它,然后绘制它。我的代码只执行一次语句。 This is how id like the code to compile

循环应该仅通过用户的提示结束。我的主要问题是我无法让循​​环连续运行。

import pylab
import pylab
import math

xs=[]
ys=[]

x0=-4.0
x1=+4.0
x=x0
n=500

dx=(x1-x0)/n

a= input("Enter a: ")
b = input("Enter b: ")
c= input("Enter c: ")

a=int(a)
b=int(b)
c=int(c)

while x<=x1:
xs.append(x)
y=(a*x**2)+(b*x+c)
ys.append(y)
x+=dx

pylab.plot(xs,ys,"rx-")
print(xs)
print(ys)
pylab.show()

2 个答案:

答案 0 :(得分:1)

你必须在while循环后缩进所有语句,程序的单个迭代版本才能工作。适当的缩进在python中至关重要。很多网站都在讨论python缩进(例如,参见here)。你也错过了允许它无限循环的外循环。

此外,您可以在每次迭代后清除图表。

import pylab
import math

xs=[]
ys=[]

x0=-4.0
x1=+4.0
x=x0
n=500

dx=(x1-x0)/n

while True:

  a=input("Enter a: ")
  b=input("Enter b: ")
  c=input("Enter c: ")

  a=int(a)
  b=int(b)
  c=int(c)

  xs=[]
  ys=[]
  x=x0  
  while x<=x1:
    xs.append(x)
    y=(a*x**2)+(b*x+c)
    x+=dx
    ys.append(y)

  pylab.plot(xs,ys,"rx-")
  print(xs)
  print(ys)
  pylab.show()
  pylab.clf()

答案 1 :(得分:0)

首先,你必须在while循环中正确地进行缩进。 其次,您的while循环只会创建列表xsys。这就是为什么你不能保持提示和剧情一次又一次地运行。所以你必须使用另一个循环重复上面的代码。这是一个例子。

import matplotlib.pyplot as plt
import math
def interactiveQPlot():
    xs=[]
    ys=[]

    x0=-4.0
    x1=+4.0
    x=x0
    n=500

    dx=(x1-x0)/n

    a= input("Enter a: ")
    b = input("Enter b: ")
    c= input("Enter c: ")

    a=int(a)
    b=int(b)
    c=int(c)

    while x<=x1:
        xs.append(x)
        y=(a*x**2)+(b*x+c)
        ys.append(y)
        x+=dx

    plt.plot(xs,ys,"rx-")
    print(xs)
    print(ys)
    plt.show()

while True:
    interactiveQPlot()