1value_when_true if condition else value_when_false
2Better Example: (thanks Mr. Burns)
3
4'Yes' if fruit == 'Apple' else 'No'
5
6Now with assignment and contrast with if syntax
7
8fruit = 'Apple'
9isApple = True if fruit == 'Apple' else False
10vs
11
12fruit = 'Apple'
13isApple = False
14if fruit == 'Apple' : isApple = True
1Python does not have a trailing if statement.
2There are two kinds of if in Python:
3
41. if statement:
5
6 if condition: statement
7 if condition:
8 block
9
102. if expression (introduced in Python 2.5)
11
12 expression_if_true if condition else expression_if_false
13
14And note, that both print a and b = a are statements. Only the a part is an expression. So if you write
15 print a if b else 0
16
17it means
18 print (a if b else 0)
19
20and similarly when you write
21 x = a if b else 0
22
23it means
24 x = (a if b else 0)
25
26Now what would it print/assign if there was no else clause? The print/assignment is still there.
27And note, that if you don't want it to be there, you can always write the regular if statement on a single line, though it's less readable and there is really no reason to avoid the two-line variant.