简体   繁体   中英

Conditional statement without using if-else in python

So here is the question. There are 2 variables having values of 3 and 5 respectively. if the user enters 3, "5" should be printed and vice versa. implement the code without using if-else. Any help would be really appreciated.

Use this:

# take integer input from user
c = int(input("Enter a number: "))

print(c == 3 and 5 or c == 5 and 3)

another thing you could try is using the tuple ternary using the (when_false, when_true)[condition] logic:

    x = int(input("Please enter a number: "))
    change_integer = (3, 5)[x == 3]
    print(change_integer)

Returns 5 when input is 3 (as the condition is 'True') & returns a 3 when input is 5 (as the condition is 'False'). Note that it will always return a 3 unless the input is 5, so this will only be useful if you only accept the two variables 3 and 5.

In python it can be simply achievable using subtraction, because conditionally we know both of the input value.

def two_variables(value):
    return 8-value

print(two_variables(5))

3

print(two_variables(3))

5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM