Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 1 min read

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

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.")

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.")

** 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.")

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.")

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.")
πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.