Python If Statement
The if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not.
Flowchart of If Statement
Let’s look at the flow of code in the Python If statements.
Syntax of If Statement in Python
Here, the condition after evaluation will be either true or false. if the statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not.
#if syntax Python
if condition:
# Statements to execute if
# condition is true
As we know, Python uses indentation to identify a block. So the block under the Python if statements will be identified as shown in the below example:
if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.
Example of Python if Statement
As the condition present in the if statements in Python is false. So, the block below the if statement is executed.
# python program to illustrate If statement
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
Output:
I am Not in if
Python If Else Statements – Conditional Statements
In both real life and programming, decision-making is crucial. We often face situations where we need to make choices, and based on those choices, we determine our next actions. Similarly, in programming, we encounter scenarios where we must make decisions to control the flow of our code.
Conditional statements in Python play a key role in determining the direction of program execution. Among these, If-Else statements are fundamental, providing a way to execute different blocks of code based on specific conditions. As the name suggests, If-Else statements offer two paths, allowing for different outcomes depending on the condition evaluated.
Types of Control Flow in Python
- Python If Statement
- Python If Else Statement
- Python Nested If Statement
- Python Elif
- Ternary Statement | Short Hand If Else Statement