Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #32026

Re: Python input function not working in 2.7 version

References <CAJ2vgs4UwT_eEstMXB2GVG+bmkfS+-tAiqv04ASH26qTc8e2HQ@mail.gmail.com>
Date 2012-10-24 21:52 +1100
Subject Re: Python input function not working in 2.7 version
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.2747.1351075943.27098.python-list@python.org> (permalink)

Show all headers | View raw


On Wed, Oct 24, 2012 at 9:37 PM, Morten Engvoldsen <mortenengv@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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Python input function not working in 2.7 version Chris Angelico <rosuav@gmail.com> - 2012-10-24 21:52 +1100

csiph-web