Decision Control Statements in Python
Decision control statements in Python allow the execution of certain parts of code based on specific conditions. This enables the program to make decisions and take different paths based on input or other factors.
Key Points on Decision Control Statements:
- Decision control statements include if, if-else, if-elif-else, and nested if statements.
- They help to control the flow of execution based on conditions evaluated as true or false.
- Indentation is critical in Python; it determines the scope of statements within the decision blocks.
- Conditions can be any expression that evaluates to a boolean value.
- Python uses and, or, and not logical operators to combine multiple conditions.
Syntax of If Statement:
Syntax Example
if condition:
# code to execute if condition is true
Example of If Statement in Python:
This example checks if a number is positive.
Code Example 1
number = 5
if number > 0:
print("The number is positive.")
Output
The number is positive.
Syntax of If-Else Statement:
Syntax Example
if condition:
# code to execute if condition is true
else:
# code to execute if condition is false
Example of If-Else Statement in Python:
This example checks if a number is even or odd.
Code Example 2
number = 4
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Output
The number is even.
Syntax of If-Elif-Else Statement:
Syntax Example
if condition1:
# code to execute if condition1 is true
elif condition2:
# code to execute if condition2 is true
else:
# code to execute if neither condition is true
Example of If-Elif-Else Statement in Python:
This example checks the grade based on the score.
Code Example 3
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
Output
Grade: B
Detailed Explanation:
- If Statement: Executes a block of code if a specified condition is true.
- If-Else Statement: Provides an alternative block of code to execute if the condition is false.
- If-Elif-Else Statement: Allows multiple conditions to be checked in sequence, executing the block of the first true condition.
- Nested If Statements: You can use an if statement inside another if statement for more complex conditions.
- Indentation: Proper indentation is crucial in Python to define the scope of control statements.
- Logical Operators: Combine conditions for more complex decision-making (e.g., and, or, not).
By effectively using decision control statements, developers can create dynamic and responsive programs that react to user input and data conditions.