In python "else if" is spelled "elif".
Also, you need a colon after the elif and the else.
Simple answer to a simple question. I had the same problem, when I first started (in the last couple of weeks).
So your code should read:
def function(a):
if a == '1':
print('1a')
elif a == '2':
print('2a')
else:
print('3a')
function(input('input:'))
Answer from Frames Catherine White on Stack OverflowVideos
In python "else if" is spelled "elif".
Also, you need a colon after the elif and the else.
Simple answer to a simple question. I had the same problem, when I first started (in the last couple of weeks).
So your code should read:
def function(a):
if a == '1':
print('1a')
elif a == '2':
print('2a')
else:
print('3a')
function(input('input:'))
Do you mean elif?
No, it's not possible (at least not with arbitrary statements), nor is it desirable. Fitting everything on one line would most likely violate PEP-8 where it is mandated that lines should not exceed 80 characters in length.
It's also against the Zen of Python: "Readability counts". (Type import this at the Python prompt to read the whole thing).
You can use a ternary expression in Python, but only for expressions, not for statements:
>>> a = "Hello" if foo() else "Goodbye"
Edit:
Your revised question now shows that the three statements are identical except for the value being assigned. In that case, a chained ternary operator does work, but I still think that it's less readable:
>>> i = 100
>>> x = 2 if i>100 else 1 if i<100 else 0
>>> x
0
>>> i = 101
>>> x = 2 if i>100 else 1 if i<100 else 0
>>> x
2
>>> i = 99
>>> x = 2 if i>100 else 1 if i<100 else 0
>>> x
1
If you only need different expressions for different cases then this may work for you:
expr1 if condition1 else expr2 if condition2 else expr3
For example:
a = "neg" if b<0 else "pos" if b>0 else "zero"