I get this error:
Traceback (most recent call last):
File "D:/Python26/PYTHON-PROGRAMME/049 bam", line 9, in <module>
ball[i][j]=sphere()
NameError: name 'ball' is not defined
when I run this code. But the ball is defined ( ball[i][j]=sphere() ). Isn`t it?
#2D-wave
#VPython
from visual import *
#ball array #ready
for i in range(5):
for y in range(5):
ball[i][j]=sphere()
ti开发者_运维技巧mer = 0
dt = 0.001
while(1):
timer += dt
for i in range(5):
for y in range(5):
#wave equation
x = sqrt(i**2 + j**2) # x = distance to the source
ball[i][j].pos.y = amplitude * sin (k * x + omega * timer)
if timer > 5:
break
When you say ball[i][j]
, you have to already have some object ball
so that you can index (twice) into it. Try this segment instead:
ball = []
for i in range(5):
ball.append([])
for y in range(5):
ball[i].append(sphere())
No, ball
is not defined. You need to create a list()
before you can start assigning to the list's indices. Similarly the nested lists need to be created before you assign to them. Try this:
ball = [None] * 5
for i in range(5):
ball[i] = [None] * 5
for j in range(5):
ball[i][j]=sphere()
or this:
ball = [[sphere() for y in range(5)] for x in range(5)]
The latter syntax which uses two list comprehensions is more idiomatic--more Pythonic, if you will.
Python doesn't know that ball
is a list. Before using it (in the first for
loop), you'll have to initialize it as
ball = []
so Python knows to treat it as a list.
no ball
is not defined. this line: ball[i][j]=sphere()
assigns value to an element of object ball
points to. There is nothing ball
points to therefore it's not possible to assign anything.
In your program, ball
is just a name that doesn't refer to anything. Using indexing like a[i]
requires that a
refer to an object that already supports indexing. Similarly, a[i][j]
requires that a[i]
refer to an object that supports indexing.
It sounds like you want it to refer to a list of lists, but this is not a great solution. You may be a lot happier performing your operations on numpy arrays, which abstract away all your looping and can really speed up computations.
精彩评论