In Python, If-Else isa fundamental conditional statement used for decision-making in programming. If...Else statement allows to execution of specific blocks of code depending on the condition is True or False.
if Statement
if statementis the most simple decision-making statement. If the condition evaluates to True, the block of code inside the if statement is executed.
If StatementExample of If Statement:
Pythoni=10# Checking if i is greater than 15ifi>15:print("10 is less than 15")print("I am Not in if")if....else Statement
if...else statement is a control statement that helps in decision-making based on specific conditions. When the if condition is False. If the condition in the if statement is not true, the else block will be executed.
If....else StatementLet's look at some examples of if-else statements.
Simple if-else
Pythoni=20# Checking if i is greater than 0ifi>0:print("i is positive")else:print("i is 0 or Negative")If Else in One-line
If we need to execute a single statement inside theifor elseblock then one-line shorthand can be used.
Pythona=-2# Ternary conditional to check if number is positive or negativeres="Positive"ifa>=0else"Negative"print(res)
Logical Operators with If..Else
We can combine multiple conditions using logical operators such asand,or, andnot.
Pythonage=25exp=10# Using '>' operator & 'and' with if-elseifage>23andexp>8:print("Eligible.")else:print("Not eligible.")Nested If Else Statement
Nested if...else statement occurs when if...elsestructure is placed inside anotherif orelse block. Nested If..else allows the execution of specific code blocks based on a series of conditional checks.
Nested if StatementExample of Nested If Else Statement:
Pythoni=10ifi==10:# First if statementifi<15:print("i is smaller than 15")# Nested - if statement# Will only be executed if statement above# it is trueifi<12:print("i is smaller than 12 too")else:print("i is greater than 15")else:print("i is not equal to 10")if…elif…else Statement
if-elif-else statement in Python is used for multi-way decision-making. This allows us to check multiple conditions sequentially and execute a specific block of code when a condition is True. If none of the conditions are true, theelse block is executed.
Example:
Pythoni=25# Checking if i is equal to 10ifi==10:print("i is 10")# Checking if i is equal to 15elifi==15:print("i is 15")# Checking if i is equal to 20elifi==20:print("i is 20")# If none of the above conditions are trueelse:print("i is not present")Similar Reads:
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice