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:
-
x
is assigned the value of 10. - The
if
statement checks whetherx
is 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:
-
num
is assigned the value of 7. - The
if
statement checks ifnum
modulo 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
if
checks ifage
is greater than or equal to 18. - If true, it prints "You are an adult" and checks if
age
is 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
if
checks ifscore
is 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...else
in a single line) to assign a value to theresult
variable based on whethernum
is 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
if
checks if the value ofword
is 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
if
checks if the listmy_list
is 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
if
checks if the variablevalue
is notNone
. - If true, it prints "The value is not None"; otherwise, it prints "The value is None".
Top comments (0)