Python Guide Sidebar

Decision Making in Python: The Ultimate Guide

Decision making in Python refers to the use of conditional statements to control the flow of the program. These statements allow the program to make decisions and execute different blocks of code based on certain conditions. Python offers several types of decision-making constructs to handle different scenarios, including if, elif, else, and logical operators.

Dive into decision-making in Python with if, elif, and else statements. Learn how to make conditional choices to control program behavior based on specific criteria.

Table of Contents

  1. What is Decision Making?
  2. Types of Decision Making
    • if Statement
    • elif Statement
    • else Statement
  3. Nested Conditionals
  4. Logical Operators in Decision Making
    • and, or, not
  5. The match Statement (Python 3.10+)
  6. Mini-Project: Age Category Program
  7. Interview Questions and Answers (Google, Amazon, TCS, Infosys, Zoho)

1. What is Decision Making?

Decision making is a programming concept where a program can make decisions based on conditions. Python allows you to control the flow of execution using conditional statements, which check whether a condition is true or false and act accordingly. These statements help to perform different actions based on different conditions, making the program flexible and dynamic.

2. Types of Decision Making

a) if Statement

The if statement is used to execute a block of code only if the specified condition is True.

Syntax:

if condition:
    # Code to execute if condition is True

Example:

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

In this example, if the condition age >= 18 is true, the program will print "You are eligible to vote.".

b) elif Statement

The elif (short for “else if”) statement is used to check multiple conditions in sequence. It comes after the if statement, and its block of code will only be executed if the condition of the if is False and the condition of elif is True.

Syntax:

if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition1 is False and condition2 is True

Example:

age = 16
if age >= 18:
    print("You are an adult.")
elif age >= 13:
    print("You are a teenager.")

Here, the program checks if age is 18 or older; if not, it checks if age is between 13 and 17. Based on the condition met, the appropriate message is printed.

c) else Statement

The else statement is used to execute a block of code when none of the preceding if or elif conditions are true.

Syntax:

if condition1:
# Code if condition1 is True
else:
# Code if condition1 is False

Example:

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

If age is less than 18, the else block will execute, and "You are a child." will be printed.

3. Nested Conditionals

A nested if statement is an if statement within another if statement. This allows you to check multiple levels of conditions.

Example:

age = 20
has_voter_id = True

if age >= 18:
    if has_voter_id:
        print("You are eligible to vote.")
    else:
        print("You are not eligible to vote due to lack of voter ID.")
else:
    print("You are not eligible to vote because of age.")

In this example:

  • The outer if checks if age is 18 or greater.
  • The inner if checks if the person has a voter ID.

If both conditions are satisfied, the person is eligible to vote; otherwise, an appropriate message is printed.

4. Logical Operators in Decision Making

Logical operators allow you to combine multiple conditions and make more complex decisions in Python.

a) and Operator

The and operator returns True if both conditions are true.

Example:

age = 20
has_voter_id = True

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

In this example, both age >= 18 and has_voter_id must be True for the if block to execute.

b) or Operator

The or operator returns True if at least one of the conditions is true.

Example:

has_passport = True
has_voter_id = False

if has_passport or has_voter_id:
    print("You are eligible to travel internationally.")
else:
    print("You are not eligible to travel internationally.")

In this case, even though has_voter_id is False, the or condition is satisfied because has_passport is True.

c) not Operator

The not operator negates a condition, making True become False and vice versa.

Example:

is_raining = False

if not is_raining:
    print("You can go for a walk.")
else:
    print("You should stay indoors.")

In this case, the not operator inverts is_raining (which is False), making the condition True and allowing the program to print "You can go for a walk.".

5. The match Statement (Python 3.10+)

The match statement, introduced in Python 3.10, is a more powerful and flexible way of handling decision-making. It is used to match patterns in complex data structures like lists or dictionaries.

Syntax:

match variable:
case pattern1:
# Code for pattern1
case pattern2:
# Code for pattern2
case _:
# Default case (like else)

Example:

command = "start"

match command:
    case "start":
        print("The process has started.")
    case "stop":
        print("The process has stopped.")
    case _:
        print("Unknown command.")

Here, the match statement evaluates command and executes the corresponding block based on its value.

6. Mini-Project: Age Category Program

Let’s create a Python program that categorizes users based on their age.

Objective:

The program will take an age input from the user and print a category (child, teenager, adult, or senior citizen) based on the input.

def age_category():
    age = int(input("Enter your age: "))
    
    if age < 13:
        print("You are a child.")
    elif 13 <= age < 18:
        print("You are a teenager.")
    elif 18 <= age < 65:
        print("You are an adult.")
    else:
        print("You are a senior citizen.")

age_category()

Sample Output:

Enter your age: 25
You are an adult.

Interview Questions and Answers


Google

Q: What will the following code output?

x = 10
if x == 10:
    print("x is 10")
else:
    print("x is not 10")

A: The output will be x is 10.


Amazon

Q: Can you use if without else?

A: Yes, in Python, if statements can stand alone without an else. else is optional.

TCS

Q: How would you use multiple conditions in an if statement?

A: You can combine conditions using logical operators like and, or, and not.

Infosys

Q: How do you handle complex decision-making in Python?

A: You can use nested if statements, logical operators, or the match statement (in Python 3.10+) to handle complex decisions.

Zoho

Q: How can we check if a value is within a specific range?

A: You can check if a value lies within a range using the and operator:

age = 25
if 18 <= age <= 60:
    print("Age is within the range.")

Conclusion

Decision making in Python is a powerful concept that enables you to control the flow of your program. Using conditional statements, logical operators, and Python’s newer features like the match statement, you can handle complex decision-making scenarios and write more efficient and adaptable code.

Decision Making