Python Language
if-elif-else
The 'if', 'elif' (short for "else if"), and 'else' statements are used for conditional branching, allowing you to execute different blocks of code based on different conditions. Let's take a deep dive into how these statements work.
if condition1: # block of code to execute if condition1 is True elif condition2: # block of code to execute if condition2 is True elif condition3: # block of code to execute if condition3 is True ... else: # block of code to execute if none of the above conditions are True
Explanation:
⤏ The 'if' statement checks a condition. If the condition is true, the code block under it is executed.
⤏ The 'elif' statement allows you to check additional conditions if the previous if or elif conditions were false.
⤏ You can have multiple elif statements to check for multiple conditions.
⤏ The 'else' statement is optional and catches anything not caught by the preceding conditions. It executes if none of the previous conditions are true.
Example:
# Python: Concepts of if-elif-else statements x = 10 if x > 10: print("x is greater than 10") elif x == 10: print("x is equal to 10") else: print("x is less than 10")
• If 'x' is greater than 10, the first 'if' condition is true, and it prints "x is greater than 10".
• If 'x' is not greater than 10 but is equal to 10, the 'elif' condition is true, and it prints "x is equal to 10".
• If 'x' is neither greater than nor equal to 10, the 'else' condition is executed, printing "x is less than 10".
x is equal to 10
Nested if-elif-else
Nested 'if-elif' statements involve placing one 'if-elif-else' construct inside another. This is useful when you need to evaluate multiple conditions in a more granular manner. Here's an example:
# Python: Concepts of Nested if-elif-else x = 10 y = 5 if x > 5: print("x is greater than 5") if y > 5: print("y is also greater than 5") elif y == 5: print("y is equal to 5") else: print("y is less than 5") elif x == 5: print("x is equal to 5") else: print("x is less than 5")
1. The outer 'if' statement checks if 'x' is greater than 5.
i. If 'x' is greater than 5, it prints "x is greater than 5".
ii. Then, it further checks 'y':
a. If 'y' is greater than 5, it prints "y is also greater than 5".
b. If 'y' is equal to 5, it prints "y is equal to 5".
c. If neither of the above conditions is true, it prints "y is less than 5".
2. If 'x' is not greater than 5, the code moves to the next 'elif' statement, checking if 'x' is equal to 5.
3. If 'x' is neither greater than nor equal to 5, it executes the 'else' block, printing "x is less than 5".
x is greater than 5 y is equal to 5
You can nest 'if-elif' statements to handle more complex conditions or to refine your logic based on multiple criteria. However, it's important to keep the code readable and not overly nested, as it can become harder to understand and maintain.
What's Next?
We've now entered the finance section on this platform, where you can enhance your financial literacy.