Working on If-Else Statements in Python
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
if condition: |
Code to check if the digit is Even or Odd
digit_list = [2,4,6,9,5] print(i,"-> odd number") |
Output: |
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:
if condition: |
Code to check if a number is odd or even
# list of numbers |
Output: |
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.
if condition1: |
Code to check if a string matches the condition
string ="BoardInfinity" |
Output: The fourth condition is true |
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:
if condition1: |
Code to check if a number is odd and divisible by 3
digit_list = [4,5,9,17,21] |
Output: 4 is an even number 5 is divisible by 3 and but not an odd no. 9 is divisible by 3 and an odd no. as well 17 is divisible by 3 and but not an odd no. 21 is divisible by 3 and an odd no. as well |