879192. The Elif Statement

Basic

The Elif Statement

Slug: the-elif-statement--100454 Difficulty: Basic Id: 879192 Topic Tags: python-conditionals Company Tags: None

Summary

The problem is about using the elif statement in Python, which allows you to specify additional conditions if the initial condition fails. The key concept involved is conditional statements and their usage.

Detailed Explanation

To solve this problem, we will use the elif statement in a simple program. The elif statement is used when you have multiple conditions to check and you want to execute different blocks of code based on those conditions.

Here's a step-by-step breakdown:

  1. Define a variable that takes user input.
  2. Use an if statement to check if the input is greater than 0.
  3. If the condition fails, use elif to check if the input is less than or equal to 0.
  4. If the input is within the range [0, 1), execute a specific block of code.
  5. If the input is outside this range, execute another specific block of code.

Here's an example:

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

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

Time complexity: O(1) Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int x = scanner.nextInt();

        if (x > 0) {
            System.out.println("The number is positive.");
        } else if (x <= 0) {
            if (x == 0) {
                System.out.println("The number is zero.");
            } else {
                System.out.println("The number is negative or zero.");
            }
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.