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

Alan Gauld alan.gauld at btinternet.com
Mon Apr 18 09:59:27 CEST 2011


"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 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:"))

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/





More information about the Tutor mailing list