Manoel Duran
Back to articlesPython Course

04. If Statements

·3 min read

undefined Here we go. For me, this article is a big milestone in our studies because it will introduce some new ways of thinking. You will begin to connect data types like booleans and operators that we learned before.

If Statements are written using the if keyword, and they are used to evaluate a condition. If the condition is True , the code block inside the if is executed. if the condition is False , Python can check another condition using elif. When none of the conditions are True we can use else.

If

a = 70
b = 150
if b > a:
  print("b is greater than a")

In this code snippet, we have two variables and an if statement that checks whether b is greater than a. In this case, the condition is True, so Python executes the print statement.

Elif

elif is short for “else if”. It allows us to check another condition when the previous if condition is False.

a = 70
b = 70
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")

In this code snippet, we have two different conditions; the first condition b > a is False . Python then moves to the elif condition and checks a == b . This condition is True , so the print statement is executed.

You can have multiple elif statements when you need to check several different conditions.

score = 72
 
if score >= 90:
  print("Grade: A")
elif score >= 80:
  print("Grade: B")
elif score >= 70:
  print("Grade: C")
elif score >= 60:
  print("Grade: D")

Python evaluates these conditions from top to bottom. As soon as it finds a condition that is True , its code block is executed, and the remaining elif and else blocks are skipped. In this example, score is 72 , so the first two conditions are False , but score >= 70 is True . So Python prints: Grade: C .

Else

The else code block is executed when neither the if nor any of the elif conditions are True . It's useful when you want to define what should happen when none of the previous conditions are satisfied.

a = 150
b = 50
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

In this example, b > a is False , and a == b is also False . Then, Python executes the else code block.

Some developers prefer to avoid unnecessary else blocks and use techniques such as early returns or guard clauses when they make the code easier to read. However, this is a more advanced topic related to code organization and clean code. But, for now, you should use if , elif and else and understand how conditional statements work.

In this article, you learned how to work with if statements, elif and else. Conditional statements are extremely important during your journey as a developer because they allow your programs to make decisions. Keep in mind that whenever your program has more than one possible path, conditional statements can be used to control the flow of your program.