Lesson 1 of 0
In Progress

Lesson #9: If…else

“If statement” is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not.

Example

num_1 = 50
num_2 = 100
if num_1 > num_2:
  print(“num_2 is greater than num_1”)

In this example, we use two variables, num_1, and num_2, which are used as part of the if statement to test whether num_2 is greater than num_1.

if-else

The if statement execute a block of statements if a condition is true. What if we want to do something else if the condition is false? We can use the else statement with if statement to execute a block of code when the condition is false.

Example

num_1 = 50
num_2 = 30
if num_1 > num_2:
  print(“num_1 is greater than num_2”)
else:
  print(“num_1 is not greater than num_2”)

if-elif-else

In that case, the if statements are executed from the top down. As soon as one of the conditions is true, the statement associated with that if is executed.

Example

num_1 = 20
num_2 = 58
if num_1 > num_2:
  print(“num_1 is greater than num_2”)
elif num_1 == num_2:
  print(“num_1 and num_2 are equal”)
else:
  print(“num_2 is greater than num_1”)

Short Hand If statement

Whenever there is only a single statement to be executed inside the if block then shorthand if can be used.

Example

num_1 = 20
num_2 = 80
if num_1 > num_2: print(“num_1 is greater than num_2”)

Short Hand If..else statement

This can be used to write the if-else statements in a single line where there is only one statement to be executed in both if and else block.

Example

num_1 = 18
num_2 = 42
print(“num_1”) if num_1 > num_2 else print(“num_2”)

💡 Note: this technique is known as Ternary Operators.

Nested If

Nested if statements mean an if statement inside another if statement.

Example

num_1 = 40

if num_1 > 20:
  print(“Num_1 is greater than 20,”)
  if num_1 > 80:
    print(“Num_1 is greater than 20 and greater than 80!”)
  else:
    print(“Num_1 is greater than 20 but not greater than 80!”)