[Tutor] Trouble executing an if statement with a string from aninput

Peter Otten __peter__ at web.de
Mon Apr 18 10:24:43 CEST 2011


Alan Gauld wrote:

> 
> "Sylvia DeAguiar" <mebesylvie at yahoo.com> wrote
> 
>> The code runs fine on python shell (from run module) but
>> when I try to execute the program from its file, it always
>> prints out c, regardless
> 
>> x = input("a, b, or c:")
>> ...
>> else:
>>     print ('c')
> 
> It looks like IDLE is running Python V3 where as the
> shell is picking up Python V2.
> 
> If you are using Linux type
> 
> $ which python
> 
> to check which version. You might want to create
> an alias for the two versions or somesuch.
> On Windows you may need to set up a different
> file association for Python.
> 
> The probl;em is with the input() function.
> In v2 input() evaluates the string typed by the user
> so that in this case it returns the numeric versions
> of the input. Thus it never equals the strings used
> in your tests. In v3 input() just returns the string
> typed by the user.

If she were using 2.x and typed an 'a' she would get a NameError.

> If you want your code to work in both Python
> versions you could explicitly convert the input()
> result to a string:
> 
>  x = str(input("a, b, or c:"))

str() doesn't magically uneval. Typing 'a' would still give you a traceback. 
If you want to emulate 3.x input() in 2.x:

try:
    input = raw_input
except NameError:
    pass

Sylvia: follow Timo's advice and add

print(repr(x)) # outer parens necessary for 3.x

If there are different versions of Python 3 on your machine and you are 
using Windows you may have run into http://bugs.python.org/issue11272 .
A workaround then may be

x = input("a, b, or c:").strip("\r")




More information about the Tutor mailing list