Qwox
Qwox

Reputation: 1

Python - How to make two very similar code blocks one/shorter?

Is it possible to reuse a function, for example, to shorten the code below?

x, y, m = 3, 5, 10

if x == 0:
    pass  # code block 1
elif x == m:
    pass  # code block 2
else:
    pass  # code block 1
    pass  # code block 2

if y == 0:
    pass  # code block 3
elif y == m:
    pass  # code block 4
else:
    pass  # code block 3
    pass  # code block 4

EDIT: A non-working example could look like this:

def func(var, code_1, code_2):
    if var != m:
        code_1
    if var != 0:
        code_2


func(x, code_block_1, code_block_2)
func(y, code_block_3, code_block_4)

EDIT2: I saw someone (Ottomated) on YouTube/Twitch using something I thought of but not in Python. Is is possible to have a similar structure in Python? The code blocks are obviously very different but the idea of inserting a variable or function name is similar.

OttomatedInterfaceFunction (sorry for the bad image quality)

Upvotes: 0

Views: 91

Answers (2)

Leonardo Scotti
Leonardo Scotti

Reputation: 1080

i guess you can try something like this:

x_val = {value: code1_as_string, value2: code2_as_string}
y_val = {value: code1_as_string, value2: code2_as_string}

exec(x_val[x])
exec(y_val[y])

but i don't thing that will be the optimal / clearest way, i think it will be better to do it in the common way with if else for every case

Upvotes: 0

Samwise
Samwise

Reputation: 71522

I might write this like:

x, y, m = 3, 5, 10

if x != m:
    pass  # code block 1
if x != 0:
    pass  # code block 2

if y != m:
    pass  # code block 3
if y != 0:
    pass  # code block 4

Upvotes: 2

Related Questions