Python input function not working in 2.7 version

Chris Angelico rosuav at gmail.com
Wed Oct 24 06:52:21 EDT 2012


On Wed, Oct 24, 2012 at 9:37 PM, Morten Engvoldsen <mortenengv at gmail.com> wrote:
> I am facing issue with input() of Python 2.7. When i run the program it
> doesn't display any line to take user input . Below is the code:
>
> But the above print function doesn't display the out put in same way. I am
> new to Python and i appreciate your help in advance.
>

Two points to note. Firstly, print is a statement in Python 2; you can
call on the print function with a future directive, but otherwise,
what you're doing there is passing a tuple to the print statement, so
it prints out like this:

('A food product having {0} fat grams and {1} total calories', 3, 270)


What you want, I think, is to explicitly use that as a format string:

print("A food product having {0} fat grams and {1} total
calories".format(fat_grams, total_calories))
A food product having 3 fat grams and 270 total calories

This then passes a single string to print, which works fine
(parentheses around a single thing do nothing; it's the comma that
makes the tuple, not the parens).

The second point to note is that, in Python 2, input() will *eval*
what the user types. Try your program and type in "1+2" (without the
quotes) at the prompt - you'll see that Python evaluates what you
typed, as though you'd entered "3". This is VERY DANGEROUS, and should
be avoided. Instead, use raw_input(), which does what you expect.

Alternatively, switch to Python 3, in which print is a function and
input() behaves exactly as you'd expect. But you'll still want to
explicitly call format().

Further reading:

http://docs.python.org/reference/simple_stmts.html#future-statements
http://docs.python.org/library/functions.html#input
http://docs.python.org/library/functions.html#raw_input
http://docs.python.org/library/stdtypes.html#str.format
http://docs.python.org/py3k/

Note, incidentally, that even though str.format() is called "new-style
formatting", there's no deprecation of "percent-style formatting"
(similar to C's sprintf function), so if you're familiar with that,
you needn't feel compelled to switch.

Hope that helps!

ChrisA



More information about the Python-list mailing list