Here are some examples of Python code using the if...else construct, along with step-by-step explanations for each:
Example 1: Basic If...Else
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
Explanation:
-
xis assigned the value of 10. - The
ifstatement checks whetherxis greater than 5. - If the condition is true, it executes the indented block under
if. - If the condition is false, it executes the indented block under
else.
Example 2: Checking Odd or Even
num = 7
if num % 2 == 0:
print("Number is even")
else:
print("Number is odd")
Explanation:
-
numis assigned the value of 7. - The
ifstatement checks ifnummodulo 2 is equal to 0 (i.e., if it's an even number). - If the condition is true, it prints "Number is even"; otherwise, it prints "Number is odd".
Example 3: Nested If...Else
age = 18
if age >= 18:
print("You are an adult")
if age >= 21:
print("You can also drink alcohol")
else:
print("You are a minor")
Explanation:
- The outer
ifchecks ifageis greater than or equal to 18. - If true, it prints "You are an adult" and checks if
ageis also greater than or equal to 21. - If the inner condition is true, it prints "You can also drink alcohol".
- If the outer condition is false, it prints "You are a minor".
Example 4: Multiple Conditions
score = 75
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Explanation:
- The
ifchecks ifscoreis greater than or equal to 90. - If true, it prints "Grade: A".
- If false, it checks the next condition (
elif) for 80, and so on. - If no conditions are true, it prints "Grade: F".
Example 5: Ternary Operator
num = 8
result = "Even" if num % 2 == 0 else "Odd"
print(result)
Explanation:
- This uses the ternary operator (
if...elsein a single line) to assign a value to theresultvariable based on whethernumis even or odd.
Example 6: String Comparison
word = "hello"
if word == "hello":
print("The word is hello")
else:
print("The word is not hello")
Explanation:
- The
ifchecks if the value ofwordis equal to the string "hello". - If true, it prints "The word is hello"; otherwise, it prints "The word is not hello".
Example 7: Checking for Empty List
my_list = []
if my_list:
print("The list is not empty")
else:
print("The list is empty")
Explanation:
- The
ifchecks if the listmy_listis not empty (evaluates toTrue). - If true, it prints "The list is not empty"; otherwise, it prints "The list is empty".
Example 8: Checking for None
value = None
if value is not None:
print("The value is not None")
else:
print("The value is None")
Explanation:
- The
ifchecks if the variablevalueis notNone. - If true, it prints "The value is not None"; otherwise, it prints "The value is None".
Top comments (0)