Python Conditional Statements: If, Elif, and Else for Decision Making

Master Python conditional statements with if-elif-else structures. Learn to build decision-making programs with practical examples including number classification and grade calculators.

12 min read

Conditional statements are the foundation of decision-making in programming. Python's if-elif-else structure allows your programs to execute different code paths based on specific conditions, making your applications intelligent and responsive to different inputs.

๐Ÿ’ก

๐ŸŽฏ What You'll Learn: In this hands-on tutorial, you'll discover:

  • Python's if-elif-else conditional statement syntax
  • How to build multi-condition decision trees
  • Practical applications with number classification and grading systems
  • Comparison operators and logical expressions
  • Best practices for writing clean conditional code
  • Common pitfalls and how to avoid them
  • Testing conditional logic with various inputs

๐Ÿค” Understanding Decision Making in Programming

Conditional statements allow programs to make decisions based on data. Instead of executing the same code every time, your program can choose different actions depending on the input or current state.

Prerequisites

Before we begin, make sure you have:

  • Understanding of Python variables and input/output
  • Python 3 installed and working on your system
  • A text editor or IDE (VS Code recommended)

๐Ÿ“ Creating Your First Conditional Program

Let's start by creating a Python file for our conditional statements examples:

ls

Output:

if-elif-else.py

The file already exists, so let's examine our first example:

cat if-elif-else.py

Output:

# Prompt the user to enter a number
number = float(input("Enter a number: "))

# Check if the number is positive, negative, or zero
if number > 0:
    print("Positive")
elif number < 0:
    print("Negative")
else:
    print("Zero")

๐Ÿ” Anatomy of If-Elif-Else Statements

Let's break down the structure of Python conditional statements:

ComponentSyntaxPurposeRequired
ifif condition:First condition to checkYes
elifelif condition:Additional conditions to checkNo
elseelse:Default action if no conditions matchNo

Key Syntax Rules:

  • Each condition ends with a colon (:)
  • Code blocks are indented (4 spaces recommended)
  • Conditions are evaluated in order from top to bottom
  • Only the first matching condition executes

๐Ÿงช Testing the Number Classification Program

Let's run our number classification program with different inputs:

Test 1: Zero

python if-elif-else.py

Input and Output:

Enter a number: 0
Zero

Test 2: Positive Number

python if-elif-else.py

Input and Output:

Enter a number: 1
Positive

Test 3: Negative Number

python if-elif-else.py

Input and Output:

Enter a number: -0.0000002
Negative
โœ…

โœ… Floating Point Precision: Notice that even very small negative numbers like -0.0000002 are correctly identified as negative. Python handles floating-point comparisons accurately for practical purposes.

๐Ÿ“Š Understanding the Decision Flow

Let's visualize how the program makes decisions:

InputCondition CheckedResultOutput
1number > 0TruePositive
-0.0000002number > 0 โ†’ number < 0False โ†’ TrueNegative
0number > 0 โ†’ number < 0 โ†’ elseFalse โ†’ False โ†’ DefaultZero

๐ŸŽ“ Building a Grade Calculator

Now let's examine a more complex example - a grading system that demonstrates multiple elif conditions:

cat if-elif-else.py

The script now contains:

score = int(input("Enter your score: "))

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

This grading system uses multiple elif statements to create a comprehensive decision tree.

๐Ÿ“ Understanding Grade Boundaries

Let's examine how the grade calculator works:

GradeScore RangeConditionDescription
A90-100score >= 90Excellent
B80-89score >= 80Good
C70-79score >= 70Satisfactory
D60-69score >= 60Needs Improvement
F0-59elseFailing

๐Ÿงช Testing the Grade Calculator

Let's test the grade calculator with various scores to understand how it works:

Test 1: Grade A (Score 90)

python if-elif-else.py

Input and Output:

Enter your score: 90
Grade: A

Test 2: Grade A (Score 91)

python if-elif-else.py

Input and Output:

Enter your score: 91
Grade: A

Test 3: Grade B (Score 89)

python if-elif-else.py

Input and Output:

Enter your score: 89
Grade: B

Test 4: Grade B (Score 80)

python if-elif-else.py

Input and Output:

Enter your score: 80
Grade: B

Test 5: Grade C (Score 75)

python if-elif-else.py

Input and Output:

Enter your score: 75
Grade: C

Test 6: Grade D (Score 65)

python if-elif-else.py

Input and Output:

Enter your score: 65
Grade: D

Test 7: Grade F (Score 59)

python if-elif-else.py

Input and Output:

Enter your score: 59
Grade: F

๐Ÿ” Why Order Matters in Elif Statements

The order of conditions in elif statements is crucial. Let's understand why:

if score >= 90:    # Checks highest grade first
    print("Grade: A")
elif score >= 80:  # Only reached if score < 90
    print("Grade: B")
elif score >= 70:  # Only reached if score < 80
    print("Grade: C")
elif score >= 60:  # Only reached if score < 70
    print("Grade: D")
else:              # Only reached if score < 60
    print("Grade: F")
if score >= 60:    # This would catch scores 60-100!
    print("Grade: D")
elif score >= 70:  # Never reached for scores 70-100
    print("Grade: C")
elif score >= 80:  # Never reached for scores 80-100
    print("Grade: B")
elif score >= 90:  # Never reached for scores 90-100
    print("Grade: A")
else:
    print("Grade: F")
โš ๏ธ

โš ๏ธ Order Matters: Always structure elif conditions from most restrictive to least restrictive (highest to lowest values) to ensure correct logic flow.

๐Ÿ”ง Comparison Operators in Python

Understanding comparison operators is essential for writing effective conditional statements:

OperatorDescriptionExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than5 > 3True
<Less than3 < 5True
>=Greater than or equal5 >= 5True
<=Less than or equal3 <= 5True

๐Ÿš€ Practical Applications of Conditional Statements

Let's explore some real-world applications:

Age Category Classifier

age = int(input("Enter your age: "))

if age < 0:
    print("Invalid age!")
elif age <= 2:
    print("Infant")
elif age <= 12:
    print("Child")
elif age <= 19:
    print("Teenager")
elif age <= 64:
    print("Adult")
else:
    print("Senior")

BMI Calculator with Health Assessment

weight = float(input("Enter your weight (kg): "))
height = float(input("Enter your height (m): "))

bmi = weight / (height ** 2)

print(f"Your BMI is: {bmi:.2f}")

if bmi < 18.5:
    print("Category: Underweight")
    print("Recommendation: Consider consulting a healthcare provider")
elif bmi < 25:
    print("Category: Normal weight")
    print("Recommendation: Maintain your current lifestyle")
elif bmi < 30:
    print("Category: Overweight")
    print("Recommendation: Consider a balanced diet and exercise")
else:
    print("Category: Obese")
    print("Recommendation: Consult a healthcare provider for guidance")

Temperature Converter with Weather Description

celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32

print(f"{celsius}ยฐC = {fahrenheit}ยฐF")

# Weather description based on Celsius
if celsius <= 0:
    description = "Freezing - Water freezes"
elif celsius <= 10:
    description = "Very Cold - Wear heavy clothing"
elif celsius <= 20:
    description = "Cool - Light jacket recommended"
elif celsius <= 30:
    description = "Comfortable - Perfect weather"
elif celsius <= 35:
    description = "Warm - Stay hydrated"
else:
    description = "Very Hot - Seek shade and drink plenty of water"

print(f"Weather: {description}")

๐ŸŽฏ Best Practices for Conditional Statements

PracticeWhy It MattersExample
Order conditions properlyEnsures correct logic flowMost restrictive first
Use descriptive conditionsImproves code readabilityif is_valid_score:
Validate inputPrevents runtime errorsif 0 <= score <= 100:

โš ๏ธ Common Pitfalls to Avoid

1. Using Assignment Instead of Comparison

# Wrong - uses assignment (=) instead of comparison (==)
if score = 90:  # This will cause a syntax error
    print("Perfect score!")

# Correct - uses comparison operator
if score == 90:
    print("Perfect score!")

2. Forgetting the Colon

# Wrong - missing colon
if score >= 90
    print("Grade: A")

# Correct - includes colon
if score >= 90:
    print("Grade: A")

3. Incorrect Indentation

# Wrong - inconsistent indentation
if score >= 90:
print("Grade: A")  # Missing indentation

# Correct - proper indentation
if score >= 90:
    print("Grade: A")

๐Ÿ“š Summary

In this tutorial, you've learned:

  • Basic if-elif-else structure for decision-making in Python
  • Comparison operators (>, <, >=, <=, ==, !=) for building conditions
  • Order importance in elif statements for correct logic flow
  • Practical applications including grading systems and classification programs
  • Best practices for writing clean, maintainable conditional code
  • Common pitfalls and how to avoid them

Key Takeaways:

  1. Conditional statements enable programs to make intelligent decisions
  2. Order matters in elif chains - most restrictive conditions first
  3. Input validation prevents runtime errors and improves user experience
  4. Descriptive conditions make code more readable and maintainable
  5. Proper indentation and syntax are crucial for Python conditional statements
โœ…

๐ŸŽ‰ Congratulations! You now understand Python conditional statements and can build decision-making programs. Practice these concepts by creating your own classification systems and decision trees.

๐Ÿš€ What's Next?

Continue your Python journey with:

  • Loops and Iteration: Learn for and while loops for repetitive tasks
  • Functions: Create reusable code blocks with parameters and return values
  • Data Structures: Master lists, dictionaries, and tuples for organizing data
  • Error Handling: Implement try-except blocks for robust programs

Ready to level up your Python skills? Check out our comprehensive Python Programming Series for more hands-on tutorials and practical examples.

O

Written by Owais

Passionate developer sharing insights on technology, development, and the art of building great software.

Related Articles

Continue exploring with these handpicked articles that complement what you just read

More Reading

One more article you might find interesting