if(Conditional) statements are an essential part of programming as they allow you to control the flow of execution based on certain conditions. In Python, if-else
statements are used to execute different blocks of code depending on the truth value of a given expression. In this tutorial, we'll learn how to use if-else
statements in Python.
Python if-else statements Syntax
if condition:
# execute this block of code if condition is True
else:
# execute this block of code if condition is False
condition
is an expression that returns a boolean value (True
or False
). If condition
is True
, the code inside the if
block is executed. If condition
is False
, the code inside the else
block is executed.
Example
Let's take a simple example to understand how if-else
statements work in Python:
age = 22
if age >= 18:
print("You are old enough to vote!")
else:
print("You are not old enough to vote yet.")
Output:
You are old enough to vote!
Nested if-else Statements
We can also have nested if-else
statements in Python, where an if
block can contain another if-else
block:
age = 24
if age >= 18:
if age == 18:
print("Congratulations! You have just become eligible to vote.")
else:
print("You are old enough to vote!")
else:
print("You are not old enough to vote yet.")
Output:
You are old enough to vote!
Multiple Conditions with elif
We can use the elif
keyword to test multiple conditions in Python:
score = 88
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Your grade is " + grade)
Output:
Your grade is B
Explore Other Related Articles
Python set tutorial
Python tuple tutorial
Python Lists tutorial
Python dictionaries comprehension tutorial
Python comparison between normal for loop and enumerate
Top comments (0)