简体   繁体   English

在 python 中不使用 if-else 的条件语句

[英]Conditional statement without using if-else in python

So here is the question.所以这就是问题所在。 There are 2 variables having values of 3 and 5 respectively.有 2 个变量的值分别为 3 和 5。 if the user enters 3, "5" should be printed and vice versa.如果用户输入 3,则应打印“5”,反之亦然。 implement the code without using if-else.在不使用 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:您可以尝试的另一件事是使用(when_false, when_true)[condition]逻辑使用元组三元组:

    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').当输入为 3 时返回 5(因为条件为“真”),当输入为 5 时返回 3(因为条件为“假”)。 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.请注意,除非输入为 5,否则它将始终返回 3,因此仅当您仅接受两个变量 3 和 5 时,这才有用。

In python it can be simply achievable using subtraction, because conditionally we know both of the input value.在 python 中,可以使用减法简单地实现,因为有条件地我们知道两个输入值。

def two_variables(value):
    return 8-value

print(two_variables(5))打印(两个变量(5))

3

print(two_variables(3))打印(两个变量(3))

5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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