DEV Community

Punitha
Punitha

Posted on

If, If-Else and If-Elif-Else Concepts

What is an If Statement?

  • The if statement checks a condition. If the condition is True, the code inside the if block is executed.

Syntax:

if condition:
    <statement>
Enter fullscreen mode Exit fullscreen mode

Example:

age = 18
if age >= 18:
     print("Eligible to vote")
Enter fullscreen mode Exit fullscreen mode

What is an If-else Statement?

  • If a condition is True, the if block executes. Otherwise, the else block executes.

Syntax:

if condition:
   <statement>
else:
   <statement>
Enter fullscreen mode Exit fullscreen mode

Example:

age = 18
if age >= 18:
     print("Eligible to vote")
else:
     print("Not eligible to vote")
Enter fullscreen mode Exit fullscreen mode

What is an If-Elif-Else Statement?

  • The if-elif-else statement is used to check multiple conditions. Python evaluates the conditions one by one and executes the block of the first condition that is True.

Syntax:

if condition1:
    <statement>
elif condition2:
    <statement>
else:
   <statement>
Enter fullscreen mode Exit fullscreen mode

Example:

marks = 75

if marks >= 90:
    print("Grade A")
elif marks >= 70:
    print("Grade B")
else:
    print("Grade C") 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)