New user's initial thoughts / criticisms of Python
Rick Johnson
rantingrickjohnson at gmail.com
Mon Nov 11 00:36:29 EST 2013
On Saturday, November 9, 2013 10:30:26 AM UTC-6, rusi wrote:
> [...]
> Well
>
> print ( {"mon":"mondays suck",
> "tue":"at least it's not monday",
> "wed":"humpday"
> }.get(day_of_week,"its some other day")
> )
> may be dense
> Separate into named dictionary and its ok (I think!)
Proper code formatting can do WONDERS for readability!
## START CODE ##
d = {
"mon":"mondays suck",
"tue":"at least it's not monday",
"wed":"humpday"
}
default = "some other day"
target = "tue"
print d.get(target, default)
target = "blah"
print d.get(target, default)
## END CODE ##
Of course you could create something "reusable" and "interface-ee".
## START CODE ##
class UsageError(Exception):
pass
class Case(object):
def __init__(self, defaultDict=None, defaultValue=None):
self.d = defaultDict or {}
self.defaultValue = defaultValue
def __str__(self):
return "Case({0})".format(self.d)
def __call__(self, key):
try:
v = self.d[key]
except KeyError:
v = self.defaultValue
return v
def __getitem__(self, k):
raise UsageError("RTFS MAN!!!")
if __name__ == '__main__':
import calendar
d = {
"mon":"mondays suck",
"tue":"at least it's not monday",
"wed":"humpday"
}
case = Case(d, "some other day")
try:
case["tue"]
except UsageError:
print 'Stopped improper useage.'
print case
lst = [s.lower() for s in calendar.weekheader(3).split(' ')]
for dayName in lst:
print "Case.__call__({0!r}) -> {1!r}".format(dayName, case(dayName))
## END CODE ##
More information about the Python-list
mailing list