The if
statement in Python is a fundamental control flow structure that allows you to execute specific code blocks based on a condition. By checking whether a condition is True
or False
, the if
statement enables decision-making in your Python programs. Combined with elif
(else if) and else
, it provides flexibility to handle multiple conditions.
Syntax and Basic Usage of the **if**
Statement
The basic structure of an if
statement in Python looks like this:
**condition**
: This is an expression that evaluates to either True
or False
.True
.age
is greater than or equal to 18, the message "You are eligible to vote." is printed.if
Statement WorksTrue
, the code inside the if
block is executed.False
, the code inside the if
block is skipped.else
for an Alternative ConditionThe else
statement provides an alternative block of code that executes when the if
condition is False
.
age
is less than 18, the message "You are not eligible to vote." is printed.elif
The elif
(else if) keyword allows you to check additional conditions when the initial if
condition is False
. You can chain multiple elif
statements together to handle different scenarios.
score
is between 80 and 89, the message "Grade: B" is printed.if
StatementsYou can place an if
statement inside another if
statement to check multiple conditions in a hierarchical way. This is called nesting.
age
is greater than or equal to 18 and the person has an ID, they are allowed to enter.if
Statements with Logical OperatorsYou can use logical operators like and
, or
, and not
to combine multiple conditions in a single if
statement.
age >= 18
and has_ticket
) must be True
for the message "You can watch the movie." to be printed.if
StatementsThe if
statement in Python is essential for controlling the flow of your programs by making decisions based on conditions. Whether you need to check one condition, multiple conditions with elif
, or handle alternative scenarios with else
, the if
statement provides the foundation for decision-making in Python. By combining it with logical operators and nesting, you can build complex and flexible control structures to make your code smarter and more dynamic.