if Statement
Introduction
In Python, the ‘if’ statement is a control flow statement that allows the programmer to structure the code based on a certain condition. If the evaluated condition is true, the code inside the ‘if’ statement block is executed.
Syntax of ‘if’ Statement
In this syntax, <condition>
is a statement evaluated as true or false, and <statements>
are the code block that executes when <condition>
is true.
How ‘if’ Statement Works
When Python encounters an ‘if’ statement, it evaluates the condition:
- If the condition is true, Python executes the code inside the ‘if’ block.
- If the condition is false, Python skips over the code inside the ‘if’ block.
Let’s consider a simple numerical example:
Here, number 10
is greater than 5
, so Python will print Number is greater than 5
.
Important to note, It is crucial to use correct indentation (four spaces by Python convention) inside the ‘if’ block. Python uses indentation to define code blocks, unlike other languages, which often use brackets.
if Statement with Logical Operators
‘if’ statements can also work with operators like and
and or
to constitute more complex conditions.
Here’s an example:
In this example, the ‘if’ statement is checking whether the number is greater than 5
and less than 15
. If both conditions are true, it will print Number is in the range 5-15
.
Note
Python evaluates boolean expressions from left to right and stops as soon as the outcome is known.
Conclusion
The ‘if’ statement is a fundamental control flow tool in Python. It directs the flow of execution based on specific conditions, enabling more flexible and dynamic code. Remember, correct indentation is key for structuring ‘if’ statements.