Control Flow - Conditional Expressions

Conditional Expression is an if-else statement in one expression. For short statements it is a much more readable and elegant form of writing. It is considered a very Pythonic form of code writing.

Here is an example:

#Conditional Expression x = "python" if 4 > 2 else "Tutorial" print(x) my_list = [1, 2, 3, 4] y = my_list if 2 in my_list else [] print(y) z = my_list if 7 in my_list else [] print(z)

Every conditional expression can be written with an if-else statement. However, for short conditions the conditional expressions are more readable than the alternative.

#Conditional Expression my_list = [1, 2, 3, 4] z = my_list if 7 in my_list else [] #if-else if 7 in my_list: x = my_list else: x = [] print(z) print(x) print(x == z)

Notice that as long as the first part of the expression is True, the last part whon't be executed. That's why the expression below is executed without raising an error.

#Conditional Expression 'This code runs perfectly fine' if True else 5/0

Exercise

  1. Write a conditional expression.
  2. Write an if-else statement that does exactly what the conditional expression does.

#Write a conditional expression #Write an if-else statement