views:

106

answers:

5

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()

timer = 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
+1  A: 

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.

mipadi
+1  A: 

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.

SilentGhost
+3  A: 

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.

John Kugelman
this will not work!! you will get `IndexError: list assignment index out of range`.
Peter
This code isn't valid. You can't assign to nonexistent list indices.
Mike Graham
ball[i] = []IndexError: list assignment index out of range
kame
I fixed the error Peter commented on 10 minutes ago FYI.
John Kugelman
+1 the list comprehension fits nicely here
Adrien Plisson
+3  A: 

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())
Peter
+1  A: 

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.

Mike Graham