Using Selection Structures

What Are Selection Structures?

Selection structures allow a program to execute different blocks of code based on conditions.

They use statements like if, else, elif (Python), else if (Java) and Boolean operators to control program flow.

Selection Structure Syntax in Python and Java

Structure Python Java
Simple If if condition: if (condition) { }
If-Else if condition: ... else: if (condition) { } else { }
Multiple Conditions if cond: ... elif cond: ... else: if (cond) { } else if (cond) { } else { }
Boolean Ops and, or, not && (AND), || (OR), ! (NOT)
Relational Ops ==, !=, <, <=, >, >= ==, !=, <, <=, >, >=
Case/Select match value:
  case 1:
    ...
  case _: # default
switch (value) {
  case 1: ... break;
  default: ...
}

Example: Using If-Else Statements

Python Implementation

This script reads an integer and uses if, elif, and else to report its sign.

num = int(input("Enter a number: "))

if num > 0:
    print("The number is positive.")
elif num < 0:
    print("The number is negative.")
else:
    print("The number is zero.")

Java Implementation

Uses if, else if, and else after reading input via Scanner.

import java.util.Scanner;

public class NumberCheck {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = scanner.nextInt();

        if (num > 0) {
            System.out.println("The number is positive.");
        } else if (num < 0) {
            System.out.println("The number is negative.");
        } else {
            System.out.println("The number is zero.");
        }
        scanner.close();
    }
}

Example: Using Case/Select Statements

Python: match-case

Uses Python 3.10+ match/case to select based on a value.

value = input("Enter command (start/stop): ")

match value:
    case "start":
        print("Starting...")
    case "stop":
        print("Stopping...")
    case _:
        print("Unknown command")

Java: switch-case

Uses switch/case for discrete selection in Java.

import java.util.Scanner;

public class SwitchDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter code (1/2): ");
        int code = sc.nextInt();

        switch (code) {
            case 1:
                System.out.println("Option 1 selected");
                break;
            case 2:
                System.out.println("Option 2 selected");
                break;
            default:
                System.out.println("Invalid option");
        }
        sc.close();
    }
}

Using Boolean and Relational Operators

  • Combine Conditions: Python: if x > 5 and y < 10:; Java: if (x > 5 && y < 10) { }
  • Range Checks: Python: if age >= 18:; Java: if (age >= 18) { }

Avoiding Common Errors

Incorrect Indentation (Python)

Error: In Python, indentation defines blocks. Misaligned lines raise IndentationError or change program meaning.

Fix: Keep each block consistently indented (spaces preferred) and align nested statements under their headers.

def total(nums):
    s = 0
    for n in nums:
        if n > 0:
        s += n   # <-- misaligned (IndentationError)
    return s
def total(nums):
    s = 0
    for n in nums:
        if n > 0:
            s += n
    return s

Note: Java doesn’t use indentation to define blocks; braces { } do. Misleading indentation still causes logic bugs when braces are omitted.

int total = 0;
for (int n : nums)
    if (n > 0)
        total += n;
        System.out.println("Added"); // looks indented under if, but isn't!
int total = 0;
for (int n : nums) {
    if (n > 0) {
        total += n;
        System.out.println("Added");
    }
}

Using = Instead of ==

Error: Using assignment in a condition instead of comparison.

Fix: Use == to compare values. Keep assignments outside conditions.

x = 5
if x = 10:      # SyntaxError: cannot assign in a condition
    print("equal")
x = 5
if x == 10:
    print("equal")
else:
    print("not equal")
int x = 5;
if (x = 10) {        // compile error: int cannot be converted to boolean
    System.out.println("equal");
}
int x = 5;
if (x == 10) {
    System.out.println("equal");
} else {
    System.out.println("not equal");
}

Note: if (flag = true) compiles because assignment yields a boolean — still a bug. Prefer if (flag) or if (flag == true) only when you must be explicit.

Logical Mistakes

Error: Misunderstanding operator precedence changes meaning (e.g. and/or in Python; &&/|| in Java).

Fix: Use parentheses to make the intended logic explicit.

# Intended: admin OR teacher, AND must have key
# Actual (wrong): 'and' binds first → teachers need key, admins don't
if is_admin or is_teacher and has_key:
    enter()
# Make intent explicit with parentheses
if (is_admin or is_teacher) and has_key:
    enter()
// Intended: (admin || teacher) && hasKey
// Actual (wrong): && binds first → teachers need key, admins don't
if (isAdmin || isTeacher && hasKey) {
    enter();
}
if ((isAdmin || isTeacher) && hasKey) {
    enter();
}

 Key Takeaways

  • Selection structures control flow via if, elif/else if, and else.
  • Boolean operators (and/&&, or/||, not/!) and relational operators (==, !=, >, etc.) enable complex conditions.
  • Watch indentation in Python and comparison operator usage in Java to avoid syntax errors.
  • Proper selection structures lead to clear, efficient, and error-free code.