In Python, the `if-else` statement is used for conditional execution. It allows you to make decisions in your code based on whether a given condition is `True` or `False`.
Here's a basic explanation along with examples:
Basic Syntax:
```python
if condition:
# code to be executed if the condition is True
else:
# code to be executed if the condition is False
```
Example:
```python
age = 25
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
```
In this example, the condition `age >= 18` is evaluated. If it's `True`, the code inside the first block (after `if`) will be executed. If it's `False`, the code inside the second block (after `else`) will be executed.
If-Elif-Else:
You can extend the `if-else` structure with `elif` (short for "else if") for additional conditions:
```python
grade = 75
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
else:
print("F")
```
In this example, the conditions are checked in order. If the first condition (`grade >= 90`) is `True`, the corresponding code is executed. If not, the next condition (`grade >= 80`) is checked, and so on. If none of the conditions is `True`, the code inside the `else` block is executed.
This allows you to create a series of mutually exclusive conditions, and the first one that evaluates to `True` will be executed.
Understanding `if-else` is fundamental for controlling the flow of your program based on different scenarios.
0 Comments