Member-only story

Unlocking the Power of if-else in Python

Python Coding
2 min readOct 13, 2024

Basic if-else Statement

The simplest form of conditional logic in Python is the if-else statement. It checks whether a condition is true or false and executes a specific block of code based on that.

x = 10

if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
x is greater than 5

Here, if x is greater than 5, the first block will run; otherwise, the second block runs.

if-elif-else for Multiple Conditions

For more complex decision-making, you can use elif (short for “else if”) to check multiple conditions.

age = 25

if age < 18:
print("You're a minor.")
elif 18 <= age < 65:
print("You're an adult.")
else:
print("You're a senior citizen.")
You're an adult.

In this example, the program checks multiple conditions and executes the first true block of code.

Nested if-else Statements

You can nest if-else statements to handle more specific conditions.

num = 10

if num > 0:
if num % 2 == 0:
print(f"{num} is a positive even number")
else:
print(f"{num} is a positive odd number")
else:
print("The number is zero or negative")
10 is a positive even number

Nested if-else statements can provide more detailed control but should be used carefully to avoid overly complex code.

Ternary Operator

Python also supports a shorthand version of the if-else statement called the ternary operator, which is useful for concise conditions.

x = 5
result = "Even" if x % 2 == 0 else "Odd"
print(result)
Odd

This one-liner evaluates the condition and assigns the value based on whether the condition is true or false.

Python Coding
Python Coding

Written by Python Coding

Learn python tips and tricks with code I Share your knowledge with us to help society. Python Quiz: https://www.clcoding.com/p/quiz-questions.html

No responses yet

Write a response