How could I make the below code shorter?
if size == "6":
element = '#pdp__select-size > li:nth-child(1) > button'
if size == "8":
element = '#pdp__select-size > li:nth-child(2) > button'
if size == "10":
element = '#pdp__select-size > li:nth-child(3) > button'
if size == "12":
element = '#pdp__select-size > li:nth-child(4) > button'
if size == "14":
element = '#pdp__select-size > li:nth-child(5) > button'
if size == "16":
element = '#pdp__select-size > li:nth-child(6) > button'
if size == "18":
element = '#pdp__select-size > li:nth-child(7) > button'
Basically, every time the size increases by 2 (from 6 > 8) etc ... I want the number in the element to increase by 1 (from 1>2) etc.
CodePudding user response:
Convert size
to an integer and perform a little arithmetic to get the value that goes in nth()
.
size_int = int(size)
if size_int % 2 == 0 and 6 <= size_int <= 18:
# size is even
nth = size_int//2 - 2
element = f"#pdp__select-size > li:nth-child({nth}) > button"
CodePudding user response:
You sir, are a genius!
Thank you that's worked perfect.