python

Conditional Statements


Logical expressions which checks for specified requirement of the program and give off True or False ( boolean expression ) is called Conditional Statement.

Python provides four primary conditional statements: 

  • if
  • else
  • elif
  • nested if

 

‘if’ Statement

The if statement is used to test a specific condition. If the condition is true, a block of code will be executed.

Syntax:

if condition:
   # block of code to be executed if the condition is true

Example:

age = 18
if age >= 18:
   print("You are an adult.")  # Output: You are an adult.
 

 

‘else’ Statement

The else statement can follow an if statement. The block of code inside else will be executed if the condition in the if statement is false.

Syntax:

if condition:
   # block of code to be executed if the condition is true
else:
   # block of code to be executed if the condition is false

Example:

age = 15
if age >= 18:
   print("You are an adult.")
else:
   print("You are not an adult.")  # Output: You are a minor.
 

 

‘elif’ Statement

The elif (short for else if) statement allows you to check multiple conditions. It must follow an if statement, and there can be multiple elif statements in a row.

Syntax:

if condition1:
   # block of code to be executed if condition1 is true
elif condition2:
   # block of code to be executed if condition2 is true
elif condition3:
   # block of code to be executed if condition3 is true
else:
   # block of code to be executed if all the above conditions are false

Example:

age = 17
if age >= 18:
   print("You are an adult.")
elif age >= 13:
   print("You are a teenager.")  # Output: You are a teenager.
else:
   print("You are a child.")
 

 

Nested if Statement

You can also nest if statements inside other if statements to create more complex conditions.

Example:

age = 20
citizen = True
if age >= 18:
   if citizen:
       print("You are eligible to vote.")  # Output: You are eligible to vote.
   else:
       print("You are not eligible to vote.")
else:
   print("You are not an adult yet.")
 

python