Variable not defined in Python for-loop

Asked

Viewed 311 times

1

I have a problem in a code that should read 4 values using raw.input().split() and then a for-loop to turn such values into float. The interpreter returns to me:

"name 'val' is not defined"

Follows the code:

p=raw.input().split()
for i in range (0,4)
    val[i]=float(p[i]) 

1 answer

1


The code has some problems. As the auto-descriptive error presented by the compiler fails to declare the list val before using it.

Maybe it’s just a matter of version, but I used the function input() to run properly.

Missed the : at the end of the for.

This only works under very specific circumstances, which is not a problem for an exercise, but would be in actual application. It’s not the best way to do it yet but it works:

val = []
p = input('Digite uma sequência de números ').split()
for i in range(0, 4):
    val.append(float(p[i]))

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I had forgotten that the equivalent of vectors in python are lists. Thanks for the help beast!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.