'Multiple Conditions or Statements in Short Hand if-else statement in python
I recently saw this if-else short hand in python and wondered is there a way to include multiple conditions and block statements in the if-else shorthand, if required.
a=int(input())
b=int(input())
print(a) if (a>b) else print("Equal") if (a==b) else print(b)
Can Something like the below code can be written in short-hand?
a=int(input())
b=int(input())
if (a>b):
print(a)
elif(a==b):
print("Equal")
elif(b>0) and (a>0):
c=a+b
print(c)
else:
print("#")
PS: The code is arbitrary just to include multiple conditions and statements.
Solution 1:[1]
If you want to write your block of code in a single line then this should work -
a=int(input())
b=int(input())
print(a) if (a>b) else print("Equal") if (a==b) else print(a+b) if (b>0) and (a>0) else print("#")
Although this doesn't reduce the codes in the original block of yours.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mehadi |