[Tutor] elif
Kent Johnson
kent37 at tds.net
Tue Jun 6 14:17:53 CEST 2006
Øyvind wrote:
> Hello.
>
> I need to make a program that does certain things every 5 minutes
> mon-friday. I have started writing it like this:
>
> if strftime('%w') == 1:
> if strftime('%M') % 5 == 0:
> n.start()
>
> elif strftime('%w') == 2:
> if strftime('%M') % 5 == 0:
> n.start()
>
> ........
>
> This seems kind of a redundant way of writing the code.
>
> I haven't gotten any statement like this to work:
> if strftime('%w') == 1 or 2 or 3:
> or
> for strftime('%w') in range(1,5):
>
> What would be a more efficient way of writing it without writing it
> several times?
First, I don't think the code you show is correct, the result of
strftime() is a string so you should compare to a string:
if strftime('%w') == '1':
You have to repeat the entire condition, so you could write:
if strftime('%w') == '1' or strftime('%w') == '2':
This could be cleaned up with a temporary variable:
dow = strftime('%w')
if dow == '1' or dow == '2':
You could also write this as
if dow in ['1', '2']:
Rather than (ab)using strftime() in this fashion, you might want to look
at datetime.datetime. You could write
now = datetime.datetime.now()
if now.weekday() in [1, 2, 3] and now.minute % 5 == 0:
Kent
More information about the Tutor
mailing list