Popular Searches
Popular Course Categories
Popular Courses

Introduction to Decision-Making in Python

Introduction to Decision-Making in Python

Conditional Statements and Decision Making

Introduction to Decision-Making in Python

Course: Python Training Course

Topic: Introduction to Decision-Making in Python

Course Link: Python Training Course at JustAcademy

Demo Registration: Register for a Course Demo

JustAcademy Homepage: Visit JustAcademy


1. Introduction to Decision-Making in Python

Decision-making is one of the fundamental concepts of programming. It allows a program to choose which statements to execute based on whether a condition is true or false. Instead of executing every instruction sequentially, a program can respond differently depending on input, calculations, and the current state of the application.

Python supports decision-making through conditional statements such as if, if-else, if-elif-else, and nested if statements. These statements work with comparison operators, logical operators, membership operators, identity operators, and Boolean expressions.

Decision-making is used in many real-world applications, including login systems, eligibility checks, student grading, shopping discounts, banking applications, inventory management, and user input validation.

Example

age = 20

if age >= 18:
    print("You are eligible to vote.")

Output:

You are eligible to vote.

In this example, Python checks whether the value of age is greater than or equal to 18. Since the condition is true, the message is displayed.

2. Learning Objectives

After studying this topic, you will be able to:

  • Understand the purpose of decision-making in Python.
  • Explain conditions, Boolean values, and conditional statements.
  • Use the if statement to execute code conditionally.
  • Use if-else to select between two alternatives.
  • Use if-elif-else to handle multiple conditions.
  • Understand nested conditional statements.
  • Combine conditions using logical operators.
  • Use comparison, membership, and identity operators in conditions.
  • Understand truthy and falsy values.
  • Avoid common errors involving indentation and conditional logic.
  • Build practical Python programs using decision-making statements.

3. What Is Decision-Making?

Decision-making is the process of evaluating a condition and selecting an appropriate action based on the result.

A condition is an expression that can be evaluated for truthiness. Many conditions use comparison operators to produce the Boolean values True or False.

Example

temperature = 35

if temperature > 30:
    print("It is a hot day.")

Output:

It is a hot day.

The condition temperature > 30 is true because 35 is greater than 30. Therefore, Python executes the indented statement inside the if block.

Why Is Decision-Making Important?

  • It allows programs to respond to different inputs.
  • It helps implement business rules and application logic.
  • It supports validation and error handling.
  • It enables programs to choose between different actions.
  • It reduces the need to write separate programs for every possible situation.
  • It makes software interactive and responsive to changing conditions.

4. Understanding Conditions in Python

A condition is an expression that determines whether a particular block of code should execute. Conditions frequently use comparison operators, logical operators, membership operators, and identity operators.

4.1 Comparison Conditions

Comparison operators compare values and return a Boolean result.

Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 10 > 5 True
< Less than 3 < 8 True
>= Greater than or equal to 10 >= 10 True
<= Less than or equal to 4 <= 7 True

Example

marks = 75

print(marks >= 40)
print(marks == 75)
print(marks < 40)

Output:

True
True
False

4.2 Logical Conditions

Logical operators combine or reverse conditions.

Operator Purpose Example
and True when both operands are truthy age >= 18 and age <= 60
or True when at least one operand is truthy day == "Saturday" or day == "Sunday"
not Reverses the truth value not is_logged_in

Example

age = 25
has_id = True

if age >= 18 and has_id:
    print("Entry permitted.")
else:
    print("Entry denied.")

Output:

Entry permitted.

Both conditions are true, so the program executes the first block.

5. Boolean Values in Decision-Making

Python has two Boolean values: True and False. They are commonly used to represent the result of a condition.

is_active = True

if is_active:
    print("Account is active.")
else:
    print("Account is inactive.")

Output:

Account is active.

The variable is_active stores the Boolean value True, so Python executes the first branch.

5.1 Conditions Do Not Always Need Comparison Operators

A condition can use a Boolean variable directly.

is_available = False

if is_available:
    print("Product is available.")
else:
    print("Product is currently unavailable.")

Output:

Product is currently unavailable.

6. The if Statement

The if statement executes a block of code only when its condition is truthy. If the condition is falsy, the statements inside that block are skipped.

Syntax

if condition:
    statement_1
    statement_2

The colon (:) marks the beginning of the conditional block. The indented statements belong to the if statement.

Example 1: Checking Positive Numbers

number = 12

if number > 0:
    print("The number is positive.")

Output:

The number is positive.

Example 2: Checking a Minimum Balance

balance = 5000

if balance >= 1000:
    print("Minimum balance requirement satisfied.")

Output:

Minimum balance requirement satisfied.

Example 3: Checking a String

password = "Python123"

if password:
    print("A password has been entered.")

Output:

A password has been entered.

A non-empty string is truthy in Python. This example only checks whether the string is non-empty; it does not validate password strength or security.

7. The if-else Statement

The if-else statement allows a program to choose between two alternative blocks. Python executes the if block when the condition is truthy and the else block when it is falsy.

Syntax

if condition:
    statements_if_true
else:
    statements_if_false

Example 1: Even or Odd Number

number = 7

if number % 2 == 0:
    print("Even number")
else:
    print("Odd number")

Output:

Odd number

The modulo operator (%) returns the remainder. An integer is even when dividing it by 2 leaves a remainder of zero.

Example 2: Pass or Fail

marks = 38

if marks >= 40:
    print("Result: Pass")
else:
    print("Result: Fail")

Output:

Result: Fail

Example 3: Login Status

is_logged_in = False

if is_logged_in:
    print("Welcome to your dashboard.")
else:
    print("Please log in to continue.")

Output:

Please log in to continue.

8. The if-elif-else Statement

The if-elif-else structure is used when a program needs to evaluate multiple conditions. Python evaluates the conditions from top to bottom and executes the first block whose condition is truthy. If no condition is truthy, the optional else block executes.

Syntax

if condition_1:
    statements_1
elif condition_2:
    statements_2
elif condition_3:
    statements_3
else:
    default_statements

Example 1: Grade Calculator

marks = 85

if marks >= 90:
    print("Grade A+")
elif marks >= 80:
    print("Grade A")
elif marks >= 70:
    print("Grade B")
elif marks >= 60:
    print("Grade C")
elif marks >= 40:
    print("Grade D")
else:
    print("Fail")

Output:

Grade A

Python checks each condition in order. Since 85 is not at least 90 but is at least 80, the program prints Grade A and skips the remaining branches.

Example 2: Temperature Classification

temperature = 18

if temperature >= 35:
    print("Very hot")
elif temperature >= 25:
    print("Warm")
elif temperature >= 15:
    print("Moderate")
else:
    print("Cold")

Output:

Moderate

Important Rule

The order of conditions matters. In a grading system, test the highest range first. If you check marks >= 40 first, a score of 85 will match that condition and the more specific higher-grade conditions will never be reached.

9. Nested if Statements

A nested if statement is an if statement placed inside another conditional block. It is useful when a decision depends on more than one level of checking.

Syntax

if outer_condition:
    if inner_condition:
        statements
    else:
        alternative_statements
else:
    outer_alternative

Example 1: Age and Identification Check

age = 22
has_id = True

if age >= 18:
    if has_id:
        print("Entry approved.")
    else:
        print("Please show identification.")
else:
    print("You must be at least 18.")

Output:

Entry approved.

Example 2: Checking Account Access

username = "admin"
password_correct = True

if username == "admin":
    if password_correct:
        print("Access granted.")
    else:
        print("Incorrect password.")
else:
    print("Unknown username.")

Output:

Access granted.

This is a learning example only. Real authentication systems should never store or compare passwords as plain text; they should use established authentication frameworks and secure password hashing.

When to Use Nested if Statements

  • When one decision should be considered only after another condition succeeds.
  • When checking prerequisites in stages.
  • When different inner conditions apply to different outer cases.

Avoid excessive nesting. When appropriate, combine simple conditions using and or move repeated logic into functions.

10. Combining Conditions with Logical Operators

Logical operators allow multiple conditions to be evaluated in a single conditional expression.

10.1 Using and

The and operator is useful when every required condition must be satisfied.

age = 25
has_license = True

if age >= 18 and has_license:
    print("Eligible to drive.")
else:
    print("Not eligible to drive.")

Output:

Eligible to drive.

10.2 Using or

The or operator is useful when at least one condition must be satisfied.

day = "Sunday"

if day == "Saturday" or day == "Sunday":
    print("It is the weekend.")
else:
    print("It is a working day.")

Output:

It is the weekend.

10.3 Using not

The not operator reverses the truth value of a condition.

is_blocked = False

if not is_blocked:
    print("Access is not blocked.")
else:
    print("Access is blocked.")

Output:

Access is not blocked.

10.4 Combining Multiple Logical Operators

age = 30
is_registered = True
has_pending_payment = False

if age >= 18 and is_registered and not has_pending_payment:
    print("Registration is complete.")
else:
    print("Registration requirements are not satisfied.")

Output:

Registration is complete.

Parentheses can improve readability when an expression combines several and and or operations.

age = 16
has_parental_permission = True

if age >= 18 or (age >= 16 and has_parental_permission):
    print("Condition satisfied.")
else:
    print("Condition not satisfied.")

Output:

Condition satisfied.

11. Truthy and Falsy Values

Python conditions do not have to contain only explicit Boolean values. Python evaluates objects according to their truth value. This behavior is known as truth-value testing.

Common falsy values include:

  • False
  • None
  • Numeric zero, such as 0, 0.0, and 0j
  • Empty strings, such as ""
  • Empty lists, such as []
  • Empty tuples, such as ()
  • Empty dictionaries, such as {}
  • Empty sets, such as set()

Most other objects are truthy by default, although custom objects can define their own truth-value behavior.

Example

items = []

if items:
    print("The list contains items.")
else:
    print("The list is empty.")

Output:

The list is empty.

Using bool()

The built-in bool() function converts a value to its Boolean truth value.

print(bool(10))
print(bool(0))
print(bool("Python"))
print(bool(""))
print(bool([1, 2]))
print(bool([]))

Output:

True
False
True
False
True
False

Important Difference: Zero and None

Although both zero and None are falsy, they represent different things. Use is None when you specifically want to check whether a value is missing or explicitly set to None.

quantity = 0

if quantity is None:
    print("Quantity is missing.")
elif quantity == 0:
    print("Quantity is zero.")
else:
    print("Quantity is greater than zero.")

Output:

Quantity is zero.

12. Decision-Making with User Input

Python's input() function allows a program to receive input from a user. The returned value is a string, so numeric input should usually be converted before performing numeric comparisons.

Example 1: Checking Age

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

if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

If the user enters 20, the program displays:

You are an adult.

This basic example assumes the user enters a valid integer. In production programs, invalid input should be handled appropriately.

Example 2: Checking Positive, Negative, or Zero

number = float(input("Enter a number: "))

if number > 0:
    print("Positive number")
elif number < 0:
    print("Negative number")
else:
    print("Zero")

Sample output for input 0:

Enter a number: 0
Zero

Example 3: Handling Invalid Numeric Input

user_input = input("Enter your age: ")

try:
    age = int(user_input)

    if age < 0:
        print("Age cannot be negative.")
    elif age < 18:
        print("You are under 18.")
    else:
        print("You are 18 or older.")

except ValueError:
    print("Please enter a valid whole number.")

The try-except structure catches a ValueError if the input cannot be converted to an integer.

13. Decision-Making with Membership Operators

Membership operators such as in and not in check whether a value exists in a sequence or collection. They are useful for validating choices and checking whether a user belongs to an approved group.

Example: Checking a Day

weekend_days = ["Saturday", "Sunday"]
day = "Sunday"

if day in weekend_days:
    print("Enjoy your weekend!")
else:
    print("Have a productive day!")

Output:

Enjoy your weekend!

Example: Checking an Allowed Role

allowed_roles = {"admin", "editor", "viewer"}
role = "editor"

if role in allowed_roles:
    print("Role is recognized.")
else:
    print("Role is not recognized.")

Output:

Role is recognized.

14. Decision-Making with Identity Operators

Identity operators check whether two references point to the same object. A common use is checking whether a variable refers to None.

result = None

if result is None:
    print("No result is available.")
else:
    print("Result is available.")

Output:

No result is available.

Use is None or is not None for this purpose. For ordinary value comparisons, use == or !=.

15. The pass Statement in Conditional Blocks

The pass statement does nothing when executed. It can serve as a placeholder when a block is required syntactically but its implementation has not been written yet.

score = 75

if score >= 50:
    pass
else:
    print("Score is below the passing mark.")

This program produces no output because the condition is true and the if block contains only pass.

The pass statement does not skip the entire conditional structure. It simply performs no action at that location.

16. The Conditional Expression (Ternary Expression)

Python supports a compact conditional expression that selects one of two values depending on a condition. It is sometimes called a ternary expression.

Syntax

value_if_true if condition else value_if_false

Example

age = 17
status = "Adult" if age >= 18 else "Minor"

print(status)

Output:

Minor

This expression is useful for simple choices. For more complex logic, a regular if-else statement is usually easier to read.

Another Example

number = 9
result = "Even" if number % 2 == 0 else "Odd"

print(result)

Output:

Odd

17. Using Decision-Making with Loops

Decision-making statements can be used inside loops to make decisions for each item or each repetition. This combination is useful for filtering data, processing records, and checking values.

Example: Identifying Even Numbers

numbers = [10, 15, 20, 25, 30]

for number in numbers:
    if number % 2 == 0:
        print(number, "is even")
    else:
        print(number, "is odd")

Output:

10 is even
15 is odd
20 is even
25 is odd
30 is even

Example: Filtering Passing Marks

marks_list = [35, 72, 48, 90, 29]

for marks in marks_list:
    if marks >= 40:
        print(marks, "Pass")
    else:
        print(marks, "Fail")

Output:

35 Fail
72 Pass
48 Pass
90 Pass
29 Fail

18. Practical Project: Student Grade and Result System

This project accepts a student's marks, validates the range, calculates a grade, and determines whether the student has passed or failed.

Program

try:
    marks = float(input("Enter marks from 0 to 100: "))

    if marks < 0 or marks > 100:
        print("Invalid marks. Enter a value between 0 and 100.")
    elif marks >= 90:
        print("Grade: A")
        print("Result: Pass")
    elif marks >= 80:
        print("Grade: B")
        print("Result: Pass")
    elif marks >= 70:
        print("Grade: C")
        print("Result: Pass")
    elif marks >= 40:
        print("Grade: D")
        print("Result: Pass")
    else:
        print("Grade: F")
        print("Result: Fail")

except ValueError:
    print("Invalid input. Please enter a numeric value.")

Sample Output

Enter marks from 0 to 100: 86
Grade: B
Result: Pass

Project Explanation

  • The program converts the user's input into a floating-point number.
  • The first condition checks whether the marks fall outside the valid range.
  • The elif branches classify the marks into grade ranges.
  • The else branch handles marks below 40.
  • The except ValueError block handles non-numeric input.

19. Practical Project: Simple Shopping Discount Calculator

This program applies a discount based on the total purchase amount.

try:
    amount = float(input("Enter purchase amount: "))

    if amount < 0:
        print("Purchase amount cannot be negative.")
    elif amount >= 5000:
        discount_rate = 0.20
    elif amount >= 2500:
        discount_rate = 0.10
    elif amount >= 1000:
        discount_rate = 0.05
    else:
        discount_rate = 0

    if amount >= 0:
        discount = amount * discount_rate
        final_amount = amount - discount

        print("Discount:", discount)
        print("Final amount:", final_amount)

except ValueError:
    print("Please enter a valid purchase amount.")

Sample Output

Enter purchase amount: 3000
Discount: 300.0
Final amount: 2700.0

Project Explanation

  • Purchase amounts below zero are rejected.
  • Different discount rates are selected using if-elif-else.
  • The discount is calculated by multiplying the amount by the selected rate.
  • The final amount is calculated by subtracting the discount from the purchase amount.
  • Invalid numeric input is handled with try-except.

20. Common Errors in Decision-Making

Error Explanation Solution
Missing colon Conditional statements require a colon at the end of the header. Write if condition:.
Incorrect indentation Python uses indentation to identify statement blocks. Indent the statements inside each block consistently.
Using = instead of == = is assignment, not equality comparison. Use == when comparing values.
Incorrect condition order A broad condition may match before a more specific condition. Arrange mutually exclusive ranges from highest to lowest or use explicit range boundaries.
Using multiple independent if statements unnecessarily Several blocks may execute when only one branch is intended. Use if-elif-else when choosing exactly one branch.
Comparing input strings with numbers input() returns a string. Convert input to int or float when appropriate.
Ignoring invalid input Conversions can raise ValueError. Validate input or use try-except.
Confusing zero with missing data Zero and None have different meanings. Use explicit checks such as value == 0 or value is None.
Writing overly complex conditions Nested logic becomes difficult to read and debug. Use parentheses, helper variables, or functions.

21. Best Practices for Decision-Making

  • Keep conditions simple and easy to understand.
  • Use meaningful variable names such as is_eligible and has_permission.
  • Use if-elif-else when only one of several alternatives should execute.
  • Use nested conditions only when they make the logic clearer.
  • Use parentheses to clarify expressions that combine multiple logical operators.
  • Validate user input before performing calculations or comparisons.
  • Handle invalid data and expected exceptions gracefully.
  • Check boundary values, such as marks of 0, 39, 40, 89, 90, and 100.
  • Avoid duplicate conditions and unreachable branches.
  • Use is None when checking for None.
  • Keep security-sensitive checks on the server side in real applications.
  • Write unit tests for important decision paths.

22. Testing Conditional Logic

Testing helps ensure that every branch of a conditional statement works as expected. A useful test plan includes ordinary values, boundary values, and invalid inputs.

Scenario Input Expected Behavior
Below passing marks 25 Display a failing result.
Exactly passing marks 40 Display a passing result.
High marks 95 Display the highest grade.
Minimum valid marks 0 Accept the input and classify the result.
Maximum valid marks 100 Accept the input and classify the result.
Negative marks -5 Display an invalid-range message.
Marks above the maximum 110 Display an invalid-range message.
Non-numeric input hello Handle the conversion error.

Boundary-value testing is especially important when conditions use operators such as >, >=, <, and <=.

23. Practice Exercises

  1. Write a program that checks whether a number is positive, negative, or zero.
  2. Write a program that checks whether a number is even or odd.
  3. Create a program that determines whether a person is eligible to vote.
  4. Write a grading program using if-elif-else.
  5. Create a program that checks whether a year is a leap year.
  6. Write a program that compares three numbers and identifies the largest one.
  7. Create a simple login-status checker using Boolean variables.
  8. Write a program that checks whether a day is a weekday or weekend.
  9. Create a shopping discount calculator with three discount levels.
  10. Write a program that checks whether a number lies between 10 and 100.
  11. Create a nested conditional program that checks age and whether identification is available.
  12. Write a program that validates numeric input and handles invalid input.
  13. Use a conditional expression to determine whether a number is even or odd.
  14. Write a program that filters a list of numbers and displays only positive values.
  15. Build a student result system that validates marks, assigns a grade, and displays pass or fail.

24. Interview Questions and Answers

Q1. What is decision-making in Python?

Answer: Decision-making allows a program to select which statements to execute based on a condition's truth value.

Q2. Which statements are commonly used for decision-making?

Answer: The main conditional structures are if, if-else, if-elif-else, and nested if statements.

Q3. What is the purpose of an if statement?

Answer: An if statement executes its block only when the condition is truthy.

Q4. What is the difference between if and if-else?

Answer: An if statement provides a conditional action. An if-else statement provides two alternative branches.

Q5. What is the purpose of elif?

Answer: The elif keyword adds another condition to test if the previous conditions were false.

Q6. What is a nested if statement?

Answer: It is an if statement placed inside another conditional block.

Q7. What is the difference between and and or?

Answer: and requires both operands to be truthy for the combined expression to be truthy, while or requires at least one operand to be truthy.

Q8. What is a Boolean value?

Answer: A Boolean value is either True or False.

Q9. What are truthy and falsy values?

Answer: Truthy values behave like true in a condition, while falsy values behave like false. Examples of falsy values include 0, None, False, and empty collections.

Q10. Why is indentation important in Python?

Answer: Indentation defines the blocks of code associated with conditional statements, loops, functions, and other compound statements.

Q11. What does the pass statement do?

Answer: The pass statement performs no action and can be used as a placeholder where Python syntax requires a statement.

Q12. What is a conditional expression?

Answer: A conditional expression selects one of two values using the form value_if_true if condition else value_if_false.

Q13. What type of value does input() return?

Answer: The input() function returns a string. Numeric input should be converted when numeric operations are required.

Q14. How can a program handle invalid numeric input?

Answer: It can use input validation and a try-except block to handle conversion errors such as ValueError.

Q15. When should nested if statements be avoided?

Answer: Avoid excessive nesting when simple logical expressions, early returns, or separate functions would make the code easier to understand.

25. Quick Revision Checklist

  • Decision-making lets a program choose actions based on conditions.
  • if executes a block when its condition is truthy.
  • if-else selects between two alternatives.
  • if-elif-else handles multiple alternatives.
  • Nested if statements support multi-level decisions.
  • Comparison operators evaluate relationships between values.
  • and, or, and not combine or reverse conditions.
  • Python supports truth-value testing for non-Boolean objects.
  • Empty collections, zero, False, and None are common falsy values.
  • Use is None to check for None.
  • Use try-except when input conversion may fail.
  • Indentation and colons are essential to correct conditional syntax.
  • Test both normal and boundary conditions.

26. Conclusion

Decision-making is an essential part of Python programming because it enables programs to respond intelligently to different situations. By using if, if-else, if-elif-else, and nested conditions, programmers can implement rules, validate inputs, classify data, and control application behavior.

Combining conditional statements with comparison, logical, membership, and identity operators makes it possible to express more complex decisions. Understanding truthy and falsy values, using correct indentation, validating user input, and testing boundary cases will help you write reliable and maintainable Python programs.

Continue Learning: Explore the Python Training Course at JustAcademy, register for a course demo, or visit the JustAcademy homepage.

whatsapp