Python

In Python, Conditional Statements are used to perform different actions based on whether a specific condition is True or False. This is the core of "Decision Making" in programming, allowing your script to branch off into different paths.

1. Theoretical Overview

A. The if Statement

The if statement is the simplest form of control flow. It evaluates a condition; if the condition is True, the indented block of code underneath it executes. If it is False, the code is skipped.

B. The else Statement

The else keyword catches anything which isn't caught by the preceding conditions. It does not take a condition of its own and acts as a "fallback" or default option.

C. The elif Statement

Short for "else if," elif allows you to check multiple expressions for True and execute a block of code as soon as one of the conditions evaluates to True. You can have an unlimited number of elif statements between an if and an else.

2. Syntax Rules

  1. Colon (:): Every if, elif, and else header must end with a colon.

  2. Indentation: Python uses whitespace (usually 4 spaces) to define the scope of the code block. If you don't indent, the code will throw an error.

  3. Order: An if statement always comes first, followed by zero or more elif statements, and finally a single (optional) else.

3. Code Implementation

Python
# Program to determine grade based on marks
marks = int(input("Enter your marks: "))

if marks >= 90:
    print("Grade: A+")
elif marks >= 80:
    print("Grade: A")
elif marks >= 70:
    print("Grade: B")
elif marks >= 60:
    print("Grade: C")
else:
    print("Grade: F (Fail)")
    print("Better luck next time!")

print("Process Complete.")

Logical Flow Explanation:

In the code above, if a user enters 85:

  1. 85 >= 90 is checked $\rightarrow$ False.

  2. 85 >= 80 is checked $\rightarrow$ True.

  3. "Grade: A" is printed.

  4. Important: Python skips the rest of the elif and else blocks entirely once a match is found.

4. Short Hand (Ternary Operator)

If you have only one statement to execute for if and one for else, you can put it all on one line. This is known as a Conditional Expression.

Python
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)

5. Multiple Conditions

You can combine multiple conditions using the Logical Operators (and, or) that you learned in the previous module.

Python if-else flowchart, AI generated
Shutterstock
Python
is_weekend = True
is_sunny = True

if is_weekend and is_sunny:
    print("Go for a picnic!")
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now