Is there a function that condense the amount of if statement I am using?

Viewed 41

My code is mostly repeated in all of the if functions, is there an way to check for the if statement without repeating the

B3 = int(wks.acell('B3').value)
B3 = B3 + 1
wks.update('B3', B3)
@bot.listen(hikari.GuildMessageCreateEvent)
async def message_count(event):
    id = event.author_id
    if id == 1:
        B3 = int(wks.acell('B3').value)
        B3 = B3 + 1
        wks.update('B3', B3)
    elif id == 2:
        B4 = int(wks.acell('B4').value)
        B4 = B4 + 1
        wks.update('B4', B4)
    elif id == 3:
        B5 = int(wks.acell('B5').value)
        B5 = B5 + 1
        wks.update('B5', B5)
    elif id == 4:
        B6 = int(wks.acell('B6').value)
        B6 = B6 + 1
        wks.update('B6', B6)
    elif id == 5:
        B7 = int(wks.acell('B7').value)
        B7 = B7 + 1
        wks.update('B7', B7)
    elif id == 6:
        B8 = int(wks.acell('B8').value)
        B8 = B8 + 1
        wks.update('B8', B8)
    elif id == 7:
        B9 = int(wks.acell('B9').value)
        B9 = B9 + 1
        wks.update('B9', B9)
3 Answers

Something this:

@bot.listen(hikari.GuildMessageCreateEvent)
async def message_count(event):
    author_id = event.author_id
    if author_id < 1 or author_id > 7:
        return
        # Or raise ValueError("message") if the value is not
        # allowed inside this range

    cell = f'B{2 + author_id}'

    wks.update(cell, int(wks.acell(cell).value) + 1)

In renamed id to author_id since id is a builtin function.

Define a dictionary mapping the ids to the cells:

id_cell = {1:'B3', 2:'B4'} #etc
    
    if id_ in id_cell:
        temp = int(wks.acell(id_cell[id_]).value)
        temp += 1
        wks.update(id_cell[id_], temp)

The entire function can be reduced to this:

async def message_count(event):
    cell = f'B{event.author_id+2}'
    wks.update(cell, wks.acell(cell).value + 1)

It might be possible to simplify it even further if only we knew what wks referred to

Related