0

I am a beginner in python and started to learn basics. I have a sample program here in python

#Simple Program Python
tf=float(input("Enter total time of run in seconds "))
delt = float(input("Enter the time step of run "))
dx = float(input("Enter the value of dx "))
xf = float(input("Enter the total length of a channel "))
n =float(tf/delt)
#t =range[n]

from array import array

m = xf/dx
for i in range(0,int(n)) :
    t[i]=i*tf/n

print("THe total time of run is %r " %tf)
print("seconds")
print("The time step is %r" %delt)
print("Number of steps is %r" %n)
print("The number of space step in X direction is %r " %m)

In the for loop, when I try to assing t[i], then it throws an error "NameError: name 't' is not defined". In some stackoverflow questions, there was suggestions to use

from array import array

But I still get an error. I tried that solution from NameError: name 'array' is not defined in python. PLease help to get rid of this error.

Thanks.

Jdbaba

1 Answer 1

2

You have to create t before you can index into it, try this:

m = xf/dx
t = []
for i in range(0,int(n)) :
    t.append(i*tf/n)

You also can take out the from array import array line. You are making and using a list not an array. If you are just learning python you probably don't need arrays and lists will do just fine.

Actually, you can even replace the entire for loop with this:

m = xf/dx
t = [i*tf/n for i in range(int(n))]

This version uses a list comprehension to accomplish the same thing. It is almost certainly faster and (in my opinion) easier to understand.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much for your reply. When I implement your suggestions, it says "IndexError: list assignment index out of range".
@Jdbaba Yup, I forgot about that part, it should be fixed now.
@ Matt Thanks so much. It is now working perfect with both the methods.
@ Matt How can I write the two dimensional array like this in python ? For i = 0 To n A(i, 0) = 0 Next i Actually I come from Vb background and trying to convert my existing code in Python. Thanks.
@Jdbaba I'm not exactly sure what you are looking for. You should probably create a new question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.