Conditional Statements


15 min.   |   Intermediate  

The if Statement

Runs a block of code only if the condition is True.

The else Statement

Use else to run code when the if condition is False.

The elif Statement

Use elif (short for “else if”) to check additional conditions.

Logical Operators

You can combine conditions using and, or, and not.

Nested Conditional Statements

You can nest conditionals inside each other.

Truthy and Falsy Values

In conditionals, Python treats certain values as False:

  • False, None, 0, "", [], {}, set()

All other values are truthy.

Conditional Statements: Exercises

Tip Conditional Statements: Exercise 1

You are given a category “A” or “B”. Create a one-hot encoded list of length 2, where:

  • Category A - [1,0]
  • Category B - [0,1]
Tip Conditional Statements: Exercise 2

Threshold the prediction of whether to buy or not by checking whether the probability is greater than 50\%:

Tip Conditional Statements: Exercise 3

Determine if the model prediction is correct by comparing predicted and actual values:

Tip Conditional Statements: Exercise 4

Compute the ReLU function of x by following the formula:

\text{ReLU}(x) = \begin{cases} x, & \text{if } x > 0 \\ 0, & \text{if } x \le 0 \end{cases}

Tip Conditional Statements: Exercise 5

Assign a class based on two features:

  • “Class A” if feature1 is greater than 5 and feature2 is less than or equal to 3,
  • “Class B” if feature1 greater than 5 and feature2 greater than 3,
  • Otherwise “Class C”.