if and Else with almost equal blocks

Asked

Viewed 551 times

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)

Don’t mind the logic of the code, it’s just a simple example.

The if and Else blocks are almost identical. Is there any way to avoid this repetition which, if frequent in the code, can make it un-elegant? Something like:

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

3 answers

6


You almost got it right with 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 don’t really recommend doing this, though; a ternary operator already somewhat impairs the readability of the code if it’s not used for something trivial. With more than one on the same line, the code quickly becomes a mess.

  • Possible Elif instead of Else?

  • @Williamlio see the edited response!

  • in fact, when chaining the ternary operator "if " the legal is to use parentheses: the precedence is not ambiguous, but the readability is improved.

  • @jsbueno can do, but the cool thing is not to chain!

2

It could also return the value in one case , and if it does not occur return the other, functioning as an "if/Else" .

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

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)
  • Yeah, the 'j' was just so the blocks had more than one line.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.