Conditional statements are used to control the flow of a program based on certain conditions or decisions. Python supports several types of conditional statements:
1. If Statement (Simple Conditional)
Used to execute a block of code if a certain condition is true.
Syntax: if condition:
2. If-Else Statement (Binary Conditional)
Used to execute one block of code if a condition is true and another block if the condition is false.
Syntax: if condition: ... else:
3. If-Elif-Else Statement (Multi-way Conditional)
Used to check multiple conditions and execute different blocks of code based on those conditions.
Syntax: if condition1: ... elif condition2: ... else:
4. Nested If Statement
Used to place an if statement inside another if statement.
Syntax: if condition1: if condition2:
5. Ternary Operator (Conditional Expression)
A shorthand way to write a simple if-else statement in a single line.
Syntax: value_if_true if condition else value_if_false
Example: Using If-Elif-Else Statement
Here's an example that demonstrates the use of an if-elif-else statement to determine a student's grade based on their score:
python
def determine_grade(score):
"""
Determine a student's grade based on their score.
Args:
score (float): The student's score (out of 100).
Returns:
str: The student's grade (A, B, C, D, or F).
"""
if score >= 90: # Condition 1: Score 90 or above
grade = "A"
elif score >= 80: # Condition 2: Score 80-89
grade = "B"
elif score >= 70: # Condition 3: Score 70-79
grade = "C"
elif score >= 60: # Condition 4: Score 60-69
grade = "D"
else: # Default: Score below 60
grade = "F"
return grade
# Example usage:
scores = [95, 82, 75, 68, 40]
for score in scores:
grade = determine_grade(score)
print(f"Score: {score}, Grade: {grade}")
Output:
code
Score: 95, Grade: A
Score: 82, Grade: B
Score: 75, Grade: C
Score: 68, Grade: D
Score: 40, Grade: F
In this example:
We define a function determine_grade that takes a score as input.
We use an if-elif-else statement to check the score against multiple conditions and assign a grade accordingly.
The elif statements allow us to check additional conditions if the previous ones are false.
The else clause serves as a default case when all conditions are false (score below 60).
Finally, we demonstrate the function's usage with a list of example scores.
Ternary Operator Example (for comparison)
Here's the equivalent logic using a ternary operator (not recommended for complex conditions):
python
def determine_grade_simple(score):
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "D" if score >= 60 else "F"
return grade
While concise, this approach can become unreadable for more complex conditions. Stick with if-elif-else for clarity and maintainability!