Τη Παρασκευή, 22 Φεβρουαρίου 2013 2:03:39 μ.μ. UTC+2, ο χρήστης Lele Gaifax έγραψε: > Ferrous Cranus <nikos.gr...@gmail.com> writes: > > > > > I'am thinking if somehting like the follwoing work: > > > > > > if( task and ( price and price.isdigit() and price.__len__() <= 3 ) and ( > > date and eval( datetime.strptime(date, '%d %m %Y').strftime('%Y-%m-%d') ) ) > > ): > > > > a) you should not (usually) call “dunder methods” directly, as they are > > (usually) exposed by builtin functions:: > > > > obj.__len__() => len(obj) > > > > b) what's the point of the eval() call above? When the strptime() > > succeds, the following strftime() call always returns a string, > > otherwise it will raise an exception and both the strftime() and the > > outer eval() won't be called. > > > > Should I write the above, I'd go for having two helper functions, for > > example:: > > > > def price_is_valid(price): > > return price and price.isdigit() and len(price) <= 3 > > > > def date_is_valid(date): > > try: > > datetime.strptime(date, '%d %m %Y') > > except (TypeError, ValueError): > > return False > > else: > > return True > > > > ... > > > > if task and price_is_valid(price) and date_is_valid(date): > > ... > > > > hth, > > ciao, lele. > > -- > > nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri > > real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia. > > l...@metapensiero.it | -- Fortunato Depero, 1929.
Let me ask it like this: How can i avoid using try: except: for checkign the date but instead check it with an if statement: if ( datetime.strptime(date, '%d %m %Y') ): date = datetime.strptime(date, '%d %m %Y').strftime('%Y-%m-%d') else: print( "Date wasn't entered properly" ) I'am trying this but if user entered date is noit on the acceptible format it raises an exception. If i surround it with eval() its still raises an excpetion. if ( datetime.strptime(date, '%d %m %Y') ): date = datetime.strptime(date, '%d %m %Y').strftime('%Y-%m-%d') else: print( "Date wasn't entered properly" ) How can i write that with an if suppresing the errors if any? -- http://mail.python.org/mailman/listinfo/python-list