Python 为什么希望输出list但是输出的是class 'list'(想使用append以及while循环把y list叠加知道x小于b),并且不确定函数以及while循环是否运行?

img

请问为什么希望输出list但是输出的是class 'list'(想使用append以及while循环把y list叠加知道x小于b),并且不确定函数以及while循环是否运行?求修改!

1.函数f(x,y) 中的0*x是什么意思
2.明显是没有执行while循环体,list列表里就没有数据
3.list是python关键字,当没有执行2时,list就是类了,所以打印class 'list'
4.最好不要用python关键字定义变量名

题主你好, list的问题有两处,

  1. 一个是 list是Python 的关键词,不能作为变量使用,因此我改为了 mylist
  2. 第二是 mylist 在 if中没有定义,直接print('y:',mylist)会报错,因此我加了定义

另外,没有进入循环是因为,a=0,b=1,x=0,而while循环条件是 x < b and x>a: 不满足 x>a 的条件,因此不能进入循环。可以修改为 x>=a即可。
望采纳

import numpy as np
import matplotlib.pyplot as plt

c = 0.4
d = 2.0
h = 0.05
a = float(input('Enter t1 '))
b = float(input('Enter t2 '))
x = 0
y = 1
def f(x,y):
    dif = -c*y**2 - d*y -0*x
    return dif

if a>=0 and b>=0 and a<=b:
    mylist = []
    while x < b and x>a:
        print('进入循环')
        k1 = h*f(x,y)
        k2 = h * f(x + h / 2, y + k1 / 2)
        k3 = h * f(x + h / 2, y + k2 / 2)
        k4 = h * f(x + h, y + k3)
        y=y+k1/6 +k2/3 + k3/3 + k4/6
        x = x +h
        mylist = [1]
        mylist.append(y)
    x= np.arange(a,b,h,dtype='float32')
    print('y:',mylist)
    print('x:',x)
else:
    print('error')