Conditionals in python

Python Conditionals Guide

Introduction to Conditionals

Some codes are so complex because of conditional statements. To code these complex codes, we need to choose or make a decision depending on the outcomes of those conditions.

Let's take an example:

Assume any integer n and find if n is positive, negative or 0.

Conditional statements used in Python are:

  1. If statements
  2. If/Else statements
  3. If/Elif/Else statements
  4. Nested conditional statements

If Statements

It is a straightforward and commonly used conditional statement. If the condition is true, the block is executed; otherwise, it is skipped.

n = 5
# Check if the number 'n' is positive
if n > 0:
    print("TRUE")

Output:

TRUE

If / Else Statements

This statement handles both conditions (true and false).

n = -15
# Check if the number is positive or not
if n > 0:
    print("TRUE")
else:
    print("FALSE")

Output:

FALSE

If / Elif / Else Statements

Used to check multiple conditions. The program executes the first true condition it finds.

n = 0
# Check if number is positive, negative, or zero
if n > 0:
    print("TRUE")
elif n == 0:
    print("ZERO")
else:
    print("FALSE")

Output:

ZERO

Nested Conditional Statements

When an If statement is present inside another If statement, it is called a nested conditional. Only executed when the outer condition is true.

n = 28
# Check if number is positive, negative, or zero
if n >= 0:
    if n == 0:
        print("ZERO")
    else:
        print("POSITIVE")
else:
    print("NEGATIVE")

Output:

POSITIVE

Conclusion

Python conditionals allow programs to make decisions based on certain conditions. Using if statements, you can execute a block of code only when a specific condition is true. If/Else statements allow handling both true and false outcomes, giving more control over program flow. If/Elif/Else statements are useful when multiple conditions need to be checked sequentially, ensuring only the first true condition is executed. Nested conditionals allow checking additional conditions within an already validated condition, making complex decision-making possible.

Understanding and using these conditional structures effectively allows Python programmers to write flexible, efficient, and readable code. Proper use of conditionals also minimizes errors and ensures that your program handles all expected scenarios correctly.

Previous Post Next Post