What is If…Else Statement in Python

Python’s if…else statement helps make decisions in programming. It executes one block of code if a condition is True and another block if the condition is False.

Basic Syntax of If…Else

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

Example 1: Checking if a Number is Positive or Negative

num = int(input("Enter a number: "))

if num > 0:
    print("The number is positive.")
else:
    print("The number is negative or zero.")

Output:

Enter a number: 5
The number is positive.

Example 2: Checking Even or Odd Number

num = int(input("Enter a number: "))

if num % 2 == 0:
    print("The number is Even.")
else:
    print("The number is Odd.")
Enter a number: 8
The number is Even.

Example 3: Grading System using If…Else

marks = int(input("Enter your marks: "))

if marks >= 90:
    print("Grade: A")
elif marks >= 80:
    print("Grade: B")
elif marks >= 70:
    print("Grade: C")
elif marks >= 60:
    print("Grade: D")
else:
    print("Grade: F")

Output:

Enter your marks: 85
Grade: B

Python’s if...else statement is a powerful tool for decision-making in programs. It enables logic-based execution based on conditions. By mastering this concept, you can create dynamic programs that respond to different inputs effectively.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *