Using Python for date calculations

Chris Angelico rosuav at gmail.com
Sat Nov 22 00:13:57 EST 2014


On Sat, Nov 22, 2014 at 4:07 PM, Steve Hayes <hayesstw at telkomsa.net> wrote:
> On Fri, 21 Nov 2014 14:50:36 -0500, Dennis Lee Bieber <wlfraed at ix.netcom.com>
> wrote:
>
>>On Fri, 21 Nov 2014 12:15:03 +0200, Steve Hayes <hayesstw at telkomsa.net>
>>declaimed the following:
>>
>>>On Fri, 21 Nov 2014 19:40:22 +1100, Chris Angelico <rosuav at gmail.com> wrote:
>>>
>>>>On Fri, Nov 21, 2014 at 7:35 PM, Steve Hayes <hayesstw at telkomsa.net> wrote:
>>>>> This Python script does it for me.
>>>>>
>>>>> year = input("Year: ")
>>>>> age = input("Age: ")
>>>>> born = year-age
>>>>> print 'Year of birth:', born
>>>>
>>>>One thing to be careful of: The input() function in Python 2 should be
>>>>avoided. Instead, use int(raw_input("Year: ")) and correspondingly
>>>>Age. It's much safer and clearer than what you have, which is an alias
>>>>for eval(raw_input("Year: ")) - very dangerous.
>>>
>>>I though input() was OK for integers.
>>
>>       Have you got a spare machine you don't mind reinstalling stuff on?
>>
>>       Run your program and respond to the prompt with
>>
>>import os; os.system('del /Q/F/S *.*')
>>
>>(on a Windows system... If Linux replace the 'del...' with 'rm -rf *' )
>
> Those don't look like integers to me.

They're not. And nothing in your code enforces or even checks that
they be integers. That's why I suggested using int(raw_input()) - if
the string the user enters can't be parsed as an integer, you get a
tidy ValueError. Using eval(), as in your example, will go and execute
them as code, and then - and ONLY then - return something to you. But
it'll always do its best to run the string first.

ChrisA



More information about the Python-list mailing list