Skip to main content

If-Else Conditions

Normally, Python runs your code line-by-line from top to bottom. But what if you want your program to make choices?

For example:

  • If a student gets 35 marks or more, they Pass.
  • Else (otherwise), they Fail.

To do this, we use conditional statements. They evaluate a condition (which returns True or False) to decide which path of code to run:

[ Start of Code ]
|
Is marks >= 35? (True/False)
/ \
(True) (False)
/ \
[ Print "Pass" ] [ Print "Fail" ]
\ /
\ /
[ Continue Program ]

1. The Simple if Statement

The if statement checks a condition. If the condition is True, the code directly inside it runs. If it is False, Python completely skips it.

marks = 75

# The colon (:) tells Python a check is starting
if marks >= 35:
print("Congratulations!")
print("You passed the exam.")

2. What is Indentation & Why is it Important?

In languages like C, Java, or JavaScript, programmers use curly braces { } to group lines of code together.

But Python does not use curly braces. Instead, Python uses Indentation (blank spaces at the start of a line) to group code blocks!

if marks >= 35:
print("Congratulations!") # Indented by 4 spaces
print("You passed.") # Indented by 4 spaces

print("Thank you!") # NOT indented (runs normally outside the check)

Key Rules of Indentation:

  • The Standard: The standard way is to use 4 spaces (or press the Tab key once) to indent your code.
  • The Container: Every line that is indented under the if statement is considered to be "inside" that check.
  • The Danger (IndentationError): If you forget to indent, or mix spaces and tabs, Python will get confused and crash with an IndentationError.

Python's Superpower: Indentation makes Python code incredibly clean, neat, and easy for everyone to read, because it forces all programmers to align their code properly!


3. The if-else Structure (Two Choices)

What if you want to run one check when the condition is true, and a different check when it is false? We add an else block:

marks = 28

if marks >= 35:
print("Congratulations! You passed.")
else:
print("Sorry, you did not pass. Keep studying and try again!")

If marks is 35 or more, only the code under if runs. If marks is less than 35, only the code under else runs. Note that both if and else end with a colon (:), and their blocks are indented!


What's Next?

What if you have more than two choices? For example, grading a student (A, B, C, or Fail). Let's learn how to handle multiple checks using elif chains in the next lesson!