Python If…Else

What are Python If…Else Statements?

The if…else construct in Python executes a block of code if a specified condition is True. If the condition evaluates to False, the code in the else block will run.

Why Use If…Else Statements?

  1. To execute different code blocks based on conditions.
  2. To handle decision-making scenarios, such as validation or comparisons.

Syntax of If…Else Statements

If Statement:

Executes a block of code if the condition is True.

if condition:
# Code to execute if condition is True

If…Else Statement:

Executes one block of code if the condition is True and another if it is False.

if condition:
# Code to execute if condition is True
else:
# Code to execute if condition is False

Elif Statement:

Adds multiple conditions to an if…else structure.

if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
else:
# Code to execute if no condition is True

Examples of Python If…Else Statements

Basic If Statement:

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

If…Else Example:

temperature = 30
if temperature > 25:
print("It's a hot day.")
else:
print("It's a cool day.")

If…Elif…Else Example:

marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
else:
print("Grade: C")

Comparison Operators in If…Else Statements

Python uses comparison operators to evaluate conditions.

OperatorMeaningExample
==Equal tox == 10
!=Not equal tox != 10
<Less thanx < 10
>Greater thanx > 10
<=Less than or equal tox <= 10
>=Greater than or equal tox >= 10

Logical Operators in If…Else Statements

You can combine multiple conditions using logical operators.

OperatorDescriptionExample
andBoth conditions Truex > 5 and x < 10
orAt least one Truex < 5 or x > 10
notNegates a conditionnot (x > 5)

Example with Logical Operators:

x = 7
if x > 5 and x < 10:
print("x is between 5 and 10.")
else:
print("x is not in the range.")

Nested If…Else Statements

You can place one if…else statement inside another.

Example:

number = 15
if number > 0:
if number % 2 == 0:
print("Positive even number.")
else:
print("Positive odd number.")
else:
print("Negative number.")

Shorthand If…Else (Ternary Operator)

Python allows you to write simple if…else statements in one line.

Syntax:

value = "Yes" if condition else "No"

Example:

age = 20
status = "Adult" if age >= 18 else "Minor"
print(status) # Output: Adult

Practical Applications of If…Else Statements

Checking User Input:

password = input("Enter your password: ")
if password == "admin123":
print("Access granted.")
else:
print("Access denied.")

Validating Numbers:

num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even number.")
else:
print("Odd number.")

Simple Login System:

username = input("Username: ")
password = input("Password: ")
if username == "admin" and password == "12345":
print("Login successful.")
else:
print("Invalid credentials.")

Common Mistakes to Avoid

  1. Indentation Errors: Python relies on indentation to define blocks of code. Ensure proper alignment.
  2. Incorrect Condition Syntax: Conditions must be valid expressions.
  3. Unreachable Else Block: Avoid conditions that make the else block redundant.

Example of Incorrect Syntax:

# Incorrect
if x = 10: # Use == for comparison
print("x is 10")

Leave a Comment