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)
Possible Elif instead of Else?
– user93774
@Williamlio see the edited response!
– Pedro von Hertwig Batista
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
@jsbueno can do, but the cool thing is not to chain!
– Pedro von Hertwig Batista