Python Forum
Is there a better way to write this case scenario?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is there a better way to write this case scenario?
#2
in python we usually use dicts in such kind of case scenario
here are two implementations, the second being more modular by implementing function

page_sizes = {1189:'A0', 841:'A1', 594:'A2', 420:'A3', 297:'A4'}
page_orientations = {True:'Portrait', False:'Landscape'}

p_size = page_sizes[max(mxd.pageSize.height, mxd.pageSize.width)]
p_orientation = page_orientations[mxd.pageSize.height>mxd.pageSize.width]
print("Page size is {} {}".format(p_size, p_orientation))
def page_info(height, width):
    page_sizes = {1189:'A0', 841:'A1', 594:'A2', 420:'A3', 297:'A4'}
    page_orientations = {True:'Portrait', False:'Landscape'}
    p_size = page_sizes[max(height, width)]
    p_orientation = page_orientations[height>width]
    return {'size':p_size, 'orientation':p_orientation}

p_info = page_info(height=mxd.pageSize.height, width=mxd.pageSize.width)
print("Page size is {size} {orientation}".format(**p_info))

Eventually, to avoid KeyError when retrieve value from page_size (i.e. hieght is not present in the dict) you may use
p_size = page_sizes.get(max(height, width), 'Unknown') # may use None if you prefer
instead of
p_size = page_sizes[max(height, width)]
also note that if height=width, page_info will return "Landscape" for orientation. You may change the code if you prefer 'Portrait' in this particular case.
Reply


Messages In This Thread
RE: Is there a better way to write this case scenario? - by buran - Sep-24-2017, 09:53 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Switch case or match case? Frankduc 9 4,886 Jan-20-2022, 01:56 PM
Last Post: Frankduc
  Help: write 'case' with Python ICanIBB 2 1,960 Jan-27-2021, 09:39 PM
Last Post: Larz60+
  How to write switch case statement in Python pyhelp 9 9,620 Nov-11-2018, 08:53 PM
Last Post: woooee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020