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

1if <condition>:
2    <statements>

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:

  1. If the condition is true, Python executes the code inside the ‘if’ block.
  2. If the condition is false, Python skips over the code inside the ‘if’ block.

Let’s consider a simple numerical example:

1num = 10
2if num > 5:
3    print("Number is greater than 5")

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:

1num = 10
2if num > 5 and num < 15:
3    print("Number is in the range 5-15")

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.