Home > Back-end >  How to make it ternary?
How to make it ternary?

Time:03-13

first_num = int(input("First number >>> "))
second_num = int(input("Second number >>> "))

if first_num >= second_num:
    diff = first_num - second_num
else:
    diff = second_num - first_num

print(f"The absolute difference of {first_num} and {second_num} is {diff}.")

CodePudding user response:

I'm assuming this is Python, although you haven't been clear.

first_num = int(input("First number >>>"))
second_num = int(input("Second number >>>"))

# Here is the ternary part: Python doesn't have an explicit ternary
# operator like C/C  , but does have this more compact if/else syntax
# which acts like one
difference = (first_num - second_num) if (first_num > second_num) else (second_num - first_num)

printf(f'The absolute difference of {first_num} and {second_num} is {difference}')

CodePudding user response:

That's a reasonably simple one in that it follows the form something if condition else something_else:

diff = first_num - second_num if first_num >= second_num else second_num - first_num

But, to be honest, if you want the absolute value, just use the abs() function:

diff = abs(first_num - second_num)

CodePudding user response:

For this you don't need any ternary logic at all, because Python has a built-in abs() function which will return the absolute:

first_num = int(input("First number >>> "))
second_num = int(input("Second number >>> "))

print(f"The absolute difference of {first_num} and {second_num} is {abs(first_num - second_num)}")

CodePudding user response:

You can use ternary operator by using 'if' statement.

In your code,

diff = first_num-second_num if first_num>=second_num else second_num-first_num

The format is as follows,

diff = (exp1) if (condition) else (exp2)

  • Related