[Tutor] dict vs several variables?

Alan Gauld alan.gauld at btinternet.com
Fri Feb 17 19:55:51 CET 2012


On 17/02/12 14:10, leam hall wrote:

> The variables input seem to be assumed to be strings

They are not assumed to be strings, they *are* strings. Users can only 
type characters at the keyboard (the usual source of input). Your 
program has to interpret those characters and convert to the right type.

It's good practice to do that as soon as possible which is why you often 
see code like:

numVal = int( raw_input("Type a number: ") )
fltVal = float( raw_input("Type a number: ") )
strVal = raw_input("Type your name: ")

This also has the advantage that you can catch user input errors early 
and request re-input. If you just store whatever the user types
("four" say) and then try to convert during the math you get an error 
far too late to fix. eg. try

print pow(int("four"), 2)

You can convert them to strings for display later but usually you
don't want to, because you will use string formatting to improve
their appearance (especially with floats).

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



More information about the Tutor mailing list