If Statements
If Statements
1. **Condition**: This is the expression that is evaluated to determine whether the associated
block of code should be executed or not. It can be any expression that evaluates to either true
or false.
2. **If Block**: If the condition evaluates to true, the code block associated with the "if
statement" is executed. This block of code is often enclosed within curly braces `{}`.
Let's consider a simple example in Python where we want to check if a number is positive:
```python
number = 5
if number > 0:
print("The number is positive.")
```
You can also include an `else` clause to specify a block of code to execute if the condition
evaluates to false. Here's an example:
```python
number = -3
if number > 0:
print("The number is positive.")
else:
print("The number is not positive.")
```
In this example, if the condition `number > 0` evaluates to false, the code block associated
with the `else` clause will be executed.
Additionally, you can include `elif` (short for "else if") clauses to check for multiple
conditions sequentially. Here's an example:
```python
number = 0
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
```
In this example, if the first condition (`number > 0`) is false, it checks the next condition
(`number < 0`). If both conditions are false, it executes the block associated with the `else`
clause.
### Conclusion:
If statements are essential for adding decision-making capabilities to your code. They allow
you to execute certain blocks of code conditionally, based on whether specified conditions
evaluate to true or false. Understanding how to use if statements helps you write programs
that can respond dynamically to different situations and inputs.