if and else with almost equal blocks

4

In Python, suppose I have a function:

def func(x):
    if x%2 == 0:
        j = x/2
        print(j)
    else:
        j = x
        print(j)

Do not mind the logic of the code, it's just a simple example.

The blocks of if and else are almost identical. Is there any way to avoid this repetition that, if frequent in code, can make it non-elegant? Something like:

def func(x):
   j = x/2, if x%2 == 0, else j=x
   print(j)
    
asked by anonymous 02.05.2018 / 05:12

3 answers

7

You've almost hit your example. It's the ternary operator :

def func(x):
    j = x/2 if x % 2 == 0 else x
    print(j)

It is not possible to make a elif , but it is possible to connect more than one ternary operator in series.

for i in range(10):
    j = x/3 if x % 3 == 0 else x/2 if x % 2 == 0 else x
    print(j)

I really do not recommend doing this, though; a ternary operator already hurts slightly the readability of the code if it is not used for something trivial. With more than one on the same line, the code quickly becomes a mess.

    
02.05.2018 / 05:15
3

It could also return the value in one case, and if it does not happen to return the other, working as an if / else.

def func(x):
    if j % 2 == 0:
        return x/2
    return x
    
02.05.2018 / 05:19
2

Instead of assigning the value to J and then displaying it, you could do the following:

def func(x):
    print(x/2 if x%2 == 0 else x)
    
02.05.2018 / 06:06