In Python, if-else statements are used to execute certain blocks of code based on whether a condition is true or false. These are essential for decision-making in programs.
Syntax of if-else
statement:
Basic Example:
Output:
In this case, since age
is 18, the condition age >= 18
evaluates to true, and the code inside the if
block is executed.
Using elif
(Else If) for multiple conditions:
You can also check multiple conditions using elif
(short for “else if”). The first condition that’s true will execute, and the others will be skipped.
Output:
In this example, the first condition age >= 18
is false, so it checks the elif
condition age >= 13
, which is true.
Nested if
Statements:
You can nest if-else
statements inside each other for more complex decision-making.
Output:
Comparison Operators:
You can use comparison operators to check conditions:
==
: Equal to!=
: Not equal to>
: Greater than<
: Less than>=
: Greater than or equal to<=
: Less than or equal to
Logical Operators:
You can combine multiple conditions using logical operators:
and
: Both conditions must be true.or
: At least one condition must be true.not
: Negates a condition (i.e., if it’s true, it becomes false and vice versa).
Examples:
Using and
:
Output:
Using or
:
Output:
Using not
:
Output:
Summary:
if
checks if a condition is true and executes the associated block.elif
checks additional conditions if the previous conditions are false.else
executes when all previous conditions are false.- Logical operators (
and
,or
,not
) help combine conditions. - You can nest
if-else
statements to handle complex logic.
These statements allow you to implement conditional logic and control the flow of your Python programs effectively.