Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonians: Is there a better way to code this in Python?

I'm a senior PHP and Perl dude, but Python is new to me. I'm enjoying learning it! I wrote the below code, but I can't shake off the feeling that it could be better written by someone with "senior level" Python skills. Are you true Pythonians up to a fun challenge?

Please note: I want the code to readable. Python is suppose to be readable - we are not writing Perl here people! (example: I like that 'weekday' is a string instead of an integer, makes it VERY clear)

import datetime
today = datetime.datetime.now()
weekday = today.strftime("%a")
hourmin = int(today.strftime("%H%M"))
print "today here is: " + today.strftime("%c") # for debug
if weekday == "Sat" or \
   (weekday == "Sun" and hourmin < 2000) or \
   (weekday == "Fri" and hourmin > 1630) or \
   (hourmin >= 1630 and hourmin < 2000) :
    print "bad time"
else:
    print "good time"
like image 420
pirhac Avatar asked Nov 17 '25 14:11

pirhac


2 Answers

You can map a day string to a lambda that takes hourmin and determines whether it is bad or not. For example:

# establish the "rules"    
bad_time = {
    'Sat': lambda h: True,    # always bad time!
    'Sun': lambda h: h < 2000,
    'Fri': lambda h: h > 1630,
}

# ... get your `weekday` and `hourmin` values

is_bad = bad_time.get(weekday, lambda h: (1630 <= h < 2000))(hourmin)
print 'bad time' if is_bad else 'good time'

edit: Follow kindall's advice.

like image 51
Santa Avatar answered Nov 20 '25 03:11

Santa


In python you can continue on the next line if you have unmatched parens, no need for the backslash. You can also do two comparisons in one boolean expression.

if (weekday == "Sat" or
    (weekday == "Sun" and hourmin < 2000) or
    (weekday == "Fri" and hourmin > 1630) or
    1630 <= hourmin < 2000):
    print "bad time"
else:
    print "good time"
like image 32
machine yearning Avatar answered Nov 20 '25 04:11

machine yearning



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!