[Tutor] dealing with user input whose value I don't know

David ldl08 at gmx.net
Fri Oct 3 09:45:46 CEST 2008


Hello Alan, dear list members,

Alan Gauld wrote:
> The solution you have already seen - use string.split(',') to separate
> the string into substrings and then convert each substring to an
> integer.
This I have now done by using eval(). But now I wonder whether that is 
actually clever because it is supposed to be similarly problematic as 
the input() function in terms of security. Alternatively I could use 
int() -- would that be the way forward?

Here is the code:

def main():
    import string

    print "This program takes the average of numbers you supply!!"

    amount = raw_input("How many numbers do you want me to work with? ")
    print "You want me to take the average of", amount, "numbers."

    numbers = raw_input("Please type the numbers, separated by commas: ")
    print "You want to know the average of the numbers:", numbers

    add = 0
    for numStr in string.split(numbers, ","):
        convNum = eval(numStr) # convert digit string to a number
        add = add + convNum # add number to variable 'add'
    print "The sum of your numbers is:", add
    average = add / float(amount)
    print "Therefore the average of your numbers is", average
main() 


Many thanks,

David



More information about the Tutor mailing list