0

How is if else working fine in this code snippet without any syntactical errors.

def even_or_odd(number):
    return 'Odd' if number % 2 else 'Even'

In Python3 if and else introduce code blocks and should be terminated by ":" (a colon), but in the code snippet above inside return statements there is no ":" after if and else.Why is python not showing syntax error

Vicky
  • 1,150
  • 10
  • 25

1 Answers1

3

if and else only require colons when used in statements. But here they are used in an expression. No colons are allowed in the expression. The Python grammar has the rule:

test: or_test ['if' or_test 'else' test] | lambdef

No need to be surprised here, it is very common for languages to use the same words or symbols for completely different things in different contexts. For example, in Python, the * is used both for multiplication and for packing and unpacking list elements.

Ray Toal
  • 79,229
  • 13
  • 156
  • 215