Login Register

What Are If…Else Statements In Python?

What are If…Else Statements?

  • An if…else statement works like a decision-making system in programming.
  • Allows a program to choose different actions based on conditions.
  • Its working process is similar to human decisions in daily life:
    • If a condition is true → do something
    • Else → do something different

Python checks the condition step by step using if…else and runs the block of code.

Why Do We Need If…Else In Our Program?

Programs give a response according to the user input, time, numbers, or any logical check, so without conditions, every program would behave the same way every time.

Let’s understand its syntax and examples:

if condition:
# Code runs when condition is True
else:
# Code runs when condition is False
  • Always remember, the indentation (space before code) is important in Python.
  • See the syntax, if the first condition becomes true, Python will run it; otherwise, go for the second condition.

Elif Statement In Python

You can add multiple conditions to an if…else statement using an elif like this:

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

1) Basic If Statement Example

  • Checking if a water bottle is full
water_level = 100      # percentage

if water_level == 100:
print("The bottle is completely full.")
  • If the condition inside the if is true, Python runs that block.
  • Here we used operator == to match the result.

2) If…Else Example

  • Checking if a shop is open or closed
current_hour = 21   # 24-hour format

if current_hour < 20:
print("The shop is open.") #Before 8 PM → shop is open
else:
print("The shop is closed.") #After 8 PM → shop is closed
  • If the first condition is true, the first message prints.
  • If not, Python jumps to the else part.

3) If…Elif…Else Example

  • This example classifies the noise level
noise = 55   # decibel level

if noise < 30:
print("Very Quiet")
elif noise < 60:
print("Moderate Noise")
else:
print("Too Loud")

Explanation of the code:

  • Python checks conditions from top to bottom
  • If the first is true → run and stop.
  • If not, check elif.
  • If none of them match → run the else block.

Comparison Operators in If…Else Statements

We can use 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 (and, or, not)

  • These operators allow you to check multiple conditions at the same time.
  • Example: Checking if a mobile battery percentage is in the “safe zone”
battery = 48   # battery percentage

if battery >= 40 and battery <= 80:
print("Battery is in the safe charging zone.")
else:
print("Battery level is outside the safe zone.")

Explanations:

  • The condition uses and, which means both conditions must be true
  • battery >= 40 → battery should be at least 40%
  • battery <= 80 → battery should not exceed 80%
  • If both are true → message shows “safe zone”.
  • If even one fails → the program goes to else.

Nested If…Else Statements In Python

Nested if…else means putting one decision block inside another decision block. We use this functionality when we need to decide within another decision.

This functionality works like checking two things step-by-step:

  • 1st question → If true → ask next question → then decide.

Example of Nested Statements:

is_registered = True
parent_permission = False

if is_registered:
if parent_permission:
print("Student is allowed to join the trip.")
else:
print("Registered but permission missing.")
else:
print("Student is not registered for the trip.")

Shorthand If…Else (Ternary Operator)

Sometimes our if…else statement only decides between two values. So instead of writing all logic in multiple lines, Python allows us to write the entire decision in a single line. This is called the ternary operator or shorthand if…else

Syntax:

variable = value_if_true if condition else value_if_false
  • If the condition is true, the first value is assigned.
  • If the condition is false, the value after else is assigned.

Simple Example:

tasks_done = 4
message = "Great productivity!" if tasks_done >= 5 else "Try to complete a few more tasks."
print(message)

What it prints:

Try to complete a few more tasks.

Practical Applications of If…Else Statements

Below are some real-life examples, where we are using if…else in our real projects.

1) Checking User Input: When users enter the password, they are passes this type of code logic.

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

2) Validating Numbers: If…else statements also used in validation where we can put multiple conditions in a single operation.

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

3) Simple Login System: This is the login system form where the program matches the username and password, then prints the appropriate message.

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

Exercise For Students

“Decide Movie Type Based on Age”

Write a Python program that asks the user for their age and prints what type of movie they are allowed to watch.

Conditions:

  • If age is 18 or above → print: “You can watch all movies, including adult-rated ones.”
  • If age is between 13 and 17 → print: “You can watch teen and family movies.”
  • If age is below 13 → print: “You can watch only kids’ movies.”

Write this logic by yourself. If you ask any questions, just write your query in our Q&A sections.