Conditional Statements

Conditional statements are used to perform different actions based on different conditions. In Python, the primary conditional statements are:

  • if
  • if-else
  • if-elif-else

The if Statement

The if statement is used to execute a block of code only if a specified condition is True.

Syntax

if condition:
    # Code to execute if the condition is True

Example

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

The if-else Statement

The if-else statement adds an alternative block of code to execute if the condition is False.

Syntax

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

Example

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

The if-elif-else Statement

The if-elif-else statement is used to check multiple conditions. It executes the first block of code where the condition is True.

Syntax

if condition1:
    # Code to execute if condition1 is True
elif condition2:
    # Code to execute if condition2 is True
else:
    # Code to execute if none of the conditions are True

Example

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

Nested Conditional Statements

Conditional statements can be nested inside one another.

Example

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

Short-Hand if and if-else

Python allows you to write conditional statements in a short-hand form when there is only one statement in the block.

Short-Hand if

if condition: action

Example

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

Short-Hand if-else

action_if_true if condition else action_if_false

Example

age = 16
print("Eligible to vote" if age >= 18 else "Not eligible to vote")

Task

Practice: Conditional Statements

Objective: Write Python scripts using different types of conditional statements.

  1. Create a Python Script: Create a file named conditional_statements.py.

  2. Check Even or Odd: Write a program that takes an integer input and prints whether the number is even or odd.

    number = int(input("Enter a number: "))
    if number % 2 == 0:
        print("Even")
    else:
        print("Odd")
    
  3. Grade Calculator: Write a program to input a student's marks and print the grade based on the following:

    • Marks >= 90: Grade A
    • Marks >= 75: Grade B
    • Marks >= 50: Grade C
    • Otherwise: Grade F
  4. Age Eligibility: Write a program to check eligibility for voting, driving, and senior citizen benefits based on age.

  5. Nested Conditions: Write a program to check if a number is positive, negative, or zero. If positive, check if it is even or odd.

Copyright © 2025 Devship. All rights reserved.

Made by imParth