What is the expected output of the following code?

What is the expected output of the following code?

def func(x):

return 1 if x % 2 != 0 else 2

print(func(func(1)))
A . The code is erroneous.
B. None
C. 2
D. 1

Answer: D

Explanation:

Topics: def conditional expression (if else) modulus operator

not equal to operator

Try it yourself:

def func(x):

return 1 if x % 2 != 0 else 2

print(func(func(1))) # 1

print(1 % 2) # 1

print(1 % 2 != 0) # True

This is a conditional expression.

1 % 2 is 1 and therefore not equal to 0

The condition is True and the inner func() function call returns 1 That 1 is passed to the outer function which will also return 1

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments