Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Kyle Woods
Kyle Woods
1,238 Points

asking for user input in python, is it required to be a string?

I was trying something out that I thought worked in the workspaces but is giving me an error when running on the windows Python command-line program. Do you need to include quotes around the input you type to set it to a string? I thought that it was automatically set as a string.

Getting this error below:

text = input('> ')

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

text = input('> ') 'hello' text 'hello'

1 Answer

I'm a bit confused as to the exact problem you are facing, in any case:

  • text = input('> ') # this is correct syntax/python
  • The builtin function input() will always return a string.
  • Once the application actually prompts for input, you don't need to surround it with quotes: if you write three that becomes the string "three"; if you write 3 that also becomes the string "3"

I'm not sure if this helps, in case it doesn't, could you please re-paste your code and format it as you have in your editor?

Kyle Woods
Kyle Woods
1,238 Points

yeah the way the code got parsed up there was kind of confusing but when I just type in hello (no quotes) when prompted for the input, it tells me that it is not defined but if I write 'hello' (quotes) its ok with it

Kyle Woods
Kyle Woods
1,238 Points
> text = input('> ')
> hello
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'hello' is not defined
>>> text = input('> ')
> 'hello'
>>> text

What I wrote above will only apply to python3.

Note that the input() builtin function behaves differently:

  • In version 2: "If the input is not syntactically valid, a SyntaxError will be raised."
  • In version 3: "...reads a line from input, converts it to a string..."

As seen here and here