I have a fragment of code with 18 if
/elif
statements. is_over
is a function that detects where the mouse is. pos
represents the position of the mouse and the buttons each are a list of x, y, width, height values.
Here is a fragment of my code:
if is_over(pos, BUTTON_DIVIDE):
print("/")
elif is_over(pos, BUTTON_MEMORY):
print("mem")
elif is_over(pos, BUTTON_CLEAR):
print("clear")
elif is_over(pos, BUTTON1):
print("1")
elif is_over(pos, BUTTON2):
print("2")
elif is_over(pos, BUTTON3):
print("3")
Although this seems fairly readable, I am wondering if there is a better approach. I am thinking I could condense this code much better with the use of a dictionary, but I am unsure how.
Use a list of tuples and a loop:
buttons = [
(BUTTON_DIVIDE, "/") , (BUTTON_MEMORY, "mem"), (BUTTON_CLEAR, "clear"),
(BUTTON1, "1"), (BUTTON2, "2"), (BUTTON3, "3")]
for button, text in buttons:
if is_over(pos, button):
print(text)
break
It is even possible to store and call functions:
def divide():
print("/")
def mem():
print("mem")
def clear():
print("clear")
buttons = [(BUTTON_DIVIDE, divide), (BUTTON_MEMORY, mem), (BUTTON_CLEAR, clear)]
for button, action in buttons:
if is_over(pos, button):
action()
break
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With