
Introduction
Python uses the if statement as a conditional statement to decide whether or not to run a piece of code. Meaning that the code block within the if statement will be executed if the program determines that the condition stated in the if statement is true.
- if statement
- if-else statement
- if-elif-else ladder
In this article, we will be explaining all of these if-else statements with code snippets and examples in a straightforward manner.
if Statement
Python uses the if statement as a conditional statement to decide whether or not to run a piece of code. Meaning that the software will execute the code block within the if statement if it determines that the condition specified in the if statement is true.
Syntax
Code to check if the digit is Even or Odd
if-else Statement
As was already said, the if statement causes the code block to run when the condition is true. Similar to this, when the declared if condition is false, the else statement is used in conjunction with the if statement to run a code block.
Syntax:
Code to check if a number is odd or even
if-elif-else ladder
Using the elif statement, you may check for many criteria and run the code block inside if any of them are true. The elif statement is comparable to the else statement in that it is optional, but unlike the else statement, more than one elif statement may follow an if statement in a code block.
Code to check if a string matches the condition
Nested if Statements
If statements are considered to be nested when one is inside another. These are typically employed to examine a variety of conditions.
Syntax:
Code to check if a number is odd and divisible by 3