[Tutor] dict vs several variables?
Peter Otten
__peter__ at web.de
Fri Feb 17 15:43:33 CET 2012
leam hall wrote:
> On 2/17/12, Peter Otten <__peter__ at web.de> wrote:
>> leam hall wrote:
>>> and they may have to have their type set
>>
>> I have no idea what you mean by "have their type set". Can you give an
>> example?
>
> Peter,
>
> The variables input seem to be assumed to be strings and I need them
> to be an integer or a float most of the time. Doing simple math on
> them.
If you are processing user input you should convert that once no matter what
the structure of your program is. Example:
#WRONG, integer conversion in many places in the code
def sum(a, b): return int(a) + int(b)
def difference(a, b): return int(a) - int(b)
a = raw_input("a ")
b = raw_input("b ")
print "a + b =", sum(a, b)
print "a - b =", difference(a, b)
#BETTER, integer conversion in a single place
def sum(a, b): return a + b
def difference(a, b): return a - b
def get_int(prompt):
return int(raw_input(prompt))
a = get_int("a ")
b = get_int("b ")
print "a + b =", sum(a, b)
print "a - b =", difference(a, b)
The second form has the added benefit that you can easily make get_int()
more forgiving (allow the user to try again when his input is not a valid
integer) or make other changes to the code (e. g. allow floating point
input).
More information about the Tutor
mailing list