DEV Community

Cover image for Conditional Statements in Python
Karthick (k)
Karthick (k)

Posted on

Conditional Statements in Python

Conditional statements control the flow of execution in a program based on specific conditions. They allow a program to execute different blocks of code depending on whether the condition is True or False.

If Statement
An if statement is used to execute a block of code only when a specified condition evaluates to True.



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

Short Hand if
Short-hand if is used to write if statements in a single line. It is useful when only one statement needs to be executed.

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

** If-Else Statement**
An if-else statement is used to execute one block of code when the condition is True and another block when the condition is False.


age = 10
if age <= 12:
    print("Travel for free.")
else:
    print("Pay for ticket.")
Enter fullscreen mode Exit fullscreen mode

If-elif-else Statement

elif statement is used to check multiple conditions in a program. It executes a block of code when its condition evaluates to True after previous conditions evaluate to False.


age = 25

if age <= 12:
    print("Child.")
elif age <= 19:
    print("Teenager.")
elif age <= 35:
    print("Young adult.")
else:
    print("Adult.")

Enter fullscreen mode Exit fullscreen mode

Nested if-else Statement

A nested if-else statement is an if-else statement placed inside another if or else block. It is used to check conditions within another condition.


age = 70
is_member = True

if age >= 60:
    if is_member:
        print("30% senior discount!")
    else:
        print("20% senior discount.")
else:
    print("Not eligible for a senior discount.")
Enter fullscreen mode Exit fullscreen mode

Top comments (0)