0

All,

I have the following code:

val1 = str(input("Enter string element 1/3: "))
val2 = int(input("Enter integer element 2/3: "))
val3 = float(input("Enter float element 3/3: "))

lst = [val1, val2, val3]
tpl = (val1, val2, val3)
dict = {"First element: ":val1, "Second element: ":val2, "Third element: ":val3}

print("/n")
print("Here is your list: ", lst)
print("Here is your tuple: ", tpl)
print("Here is your dictionary ", dict)

print("/n")
val4 = input("Add a new str list element: ")
lst.append(val4)
print("Here is your new list ", lst) 

But i seem to get this return:

Traceback (most recent call last):
  File "C:/Python27/Test2", line 1, in <module>
    val1 = str(input("Enter string element 1/3: "))
  File "<string>", line 1, in <module>
NameError: name 'test' is not defined

However, int and float both work - so why doesn't string? It's saying that 'test' isn't defined, but i thought it because defined after the user inputted the word?

Any help would be greatly appreciated.

Regards,

1
  • "/n" is not a newline; "\n" is. Commented Aug 11, 2014 at 16:19

1 Answer 1

1

You want to use raw_input instead of input in Python 2.

>>> float(input(": "))
: test
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'test' is not defined

vs

>>> float(raw_input(": "))
: test
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): test

input evaluates its input as an expression, so if you enter test at its prompt, it tries to evaluate that as a name.

raw_input always returns the string you type as a str object, so you still need to take care that what you type is a value input for whatever you intend to pass it to.

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

Comments

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.