Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to write multiple elif statements in python?

Tags:

python

pygame

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.

like image 286
Bdizzy Avatar asked Dec 30 '22 14:12

Bdizzy


1 Answers

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
like image 169
Rabbid76 Avatar answered Jan 02 '23 03:01

Rabbid76