In Python, the “if…else” statement is used to create conditional logic in your code. It allows you to specify a block of code to be executed if a particular condition is true, and another block of code to be executed if that condition is false. This statement is particularly useful for controlling the flow of your code based on certain conditions, and is an essential tool for writing effective and efficient Python programs.
x = 10
y = 5
if x > y:
print("x is greater than y")
else:
print("y is greater than x")
Output: x is greater than y
Explanation: In this example, we have two variables “x” and “y”. We then use the “if…else” statement to check if “x” is greater than “y”. Since “x” is indeed greater than “y”, the first block of code is executed and we get the output “x is greater than y”.
age = 25
if age >= 18:
print("You are an adult")
if age >= 21:
print("You are eligible to vote and drink")
else:
print("You are eligible to vote but not drink")
else:
print("You are a minor")
Output:
You are an adult
You are eligible to vote but not drink
Explanation: In this example, we use a nested “if” statement within the “if…else” statement. We first check if the age is greater than or equal to 18. If it is, we print “You are an adult” and then check if the age is greater than or equal to 21. If it is, we print “You are eligible to vote and drink”. If the age is between 18 and 21, we print “You are eligible to vote but not drink”. If the age is less than 18, we print “You are a minor”. Since the age in this example is 25, the output will be “You are an adult” and “You are eligible to vote but not drink”.
age = 25
is_student = True
if age >= 18 and is_student:
print("You are an adult student")
else:
print("You are not an adult student")
Output: You are an adult student
Explanation: In this example, we use boolean operators “and” to check if the age is greater than or equal to 18 and if “is_student” variable is true. Since both conditions are true, the first block of code is executed and we get the output “You are an adult student”.
x = 10
if x < 0:
print("x is negative")
elif x == 0:
print("x is zero")
else:
print("x is positive")
Output: x is positive
Explanation: In this example, we use the “elif” statement to check for multiple conditions. We first check if “x” is less than 0, and if it is, we print “x is negative”. If “x” is not less than 0, we check if “x” is equal to 0, and if it is, we print “x is zero”. If “x” is not less than 0 or equal to 0, we print “x is positive”. Since “x” in this example is 10, the output will be “x is positive”.
x = 10
y = 5
output = "x is greater than y" if x > y else "y is greater than x"
print(output)
Output: x is greater than y
Explanation: In this example, we use a ternary operator to simplify the “if…else” statement. We set the value of “output” to “x is greater than y” if “x” is greater than “y”, otherwise we set it to “y is greater than x”. We then print the value of “output”. Since “x” in this example is greater than “y”, the output will be “x is greater than y”.
def find_max(a, b):
if a > b:
return a
else:
return b
print(find_max(5, 10))
Output: 10
Explanation: In this example, we use the “if…else” statement within a function. The function takes two arguments “a” and “b”, and checks if “a” is greater than “b”. If it is, the function returns “a”, otherwise it returns “b”. We then call the function with the arguments 5 and 10, and print the returned value. Since 10 is greater than 5, the output will be 10.
numbers = [1, 2, 3, 4, 5]
if len(numbers) > 5:
print("The list is too long")
else:
print("The list is of reasonable length")
Output: The list is of reasonable length
Explanation: In this example, we use the “if…else” statement to check the length of a list. We first check if the length of the “numbers” list is greater than 5. If it is, we print “The list is too long”. If the length of the list is not greater than 5, we print “The list is of reasonable length”. Since the length of the “numbers” list in this example is 5, the output will be “The list is of reasonable length”.
person = {
"name": "John",
"age": 25,
"gender": "male"
}
if "gender" in person:
print(f"{person['name']} is {person['gender']}")
else:
print("No gender information available")
Output: John is male
Explanation: In this example, we use the “if…else” statement to check if a key exists in a dictionary. We first check if the key “gender” exists in the “person” dictionary. If it does, we print the name of the person and their gender. If the key does not exist, we print “No gender information available”. Since the “gender” key exists in the “person” dictionary in this example, the output will be “John is male”.
try:
x = int("hello")
print(x)
except:
print("An error occurred")
Output: An error occurred
Explanation: In this example, we use the “try…except” statement with the “if…else” statement to handle exceptions. We try to convert the string “hello” to an integer using the “int” function, which will raise a ValueError. We use the “except” statement to catch the error and print “An error occurred”. Since the code in the “try” block raises an error, the output will be “An error occurred”.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
Output
1 is odd
2 is even
3 is odd
4 is even
5 is odd
Explanation: In this example, we use the “if…else” statement within a loop. We iterate over each number in the “numbers” list, and check if the number is even or odd using the modulus operator. If the number is even, we print that it is even. If the number is odd, we print that it is odd. The output shows that the numbers 2 and 4 are even, while the others are odd.
x = True
y = False
if x and not y:
print("Both conditions are True")
else:
print("At least one condition is False")
Output: Both conditions are True
Explanation: In this example, we use the “if…else” statement with boolean values. We check if “x” is True and “y” is not True (which is equivalent to False). If both conditions are True, we print “Both conditions are True”. If at least one condition is False, we print “At least one condition is False”. Since “x” is True and “y” is False in this example, the output will be “Both conditions are True”.
name = "Alice"
if name == "Alice":
print("Welcome, Alice!")
else:
print("You are not Alice.")
Output: Welcome, Alice!
Explanation: In this example, we use the “if…else” statement to compare a string. We check if the “name” variable is equal to “Alice”. If it is, we print “Welcome, Alice!”. If it is not, we print “You are not Alice.”. Since the “name” variable in this example is “Alice”, the output will be “Welcome, Alice!”.
def is_even(num):
if num % 2 == 0:
return True
else:
return False
print(is_even(2))
print(is_even(3))
Output:
True
False
Explanation: In this example, we use the “if…else” statement within a function. The “is_even” function takes a number as an argument, and checks if the number is even or odd using the modulus operator. If the number is even, the function returns True. If the number is odd, the function returns False. We then call the function with the numbers 2 and 3, and print the results. The output shows that 2 is even (which returns True), while 3 is odd (which returns False).
age = 25
income = 50000
if age > 18 and income > 30000:
print("You are eligible for a loan")
else:
print("You are not eligible for a loan")
Output: You are eligible for a loan
Explanation: In this example, we use the “if…else” statement with multiple conditions. We check if the “age” variable is greater than 18 AND the “income” variable is greater than 30000. If both conditions are True, we print “You are eligible for a loan”. If at least one condition is False, we print “You are not eligible for a loan”. Since the “age” variable is 25 and the “income” variable is 50000 in this example, both conditions are True, so the output will be “You are eligible for a loan”.
x = 10
y = 5
if x > y:
if x - y > 5:
print("The difference is greater than 5")
else:
print("The difference is less than or equal to 5")
else:
print("The second number is greater than or equal to the first number")
Output: The difference is greater than 5
Explanation: In this example, we use the “if…else” statement with nested statements. We first check if the “x” variable is greater than the “y” variable. If it is, we check if the difference between “x” and “y” is greater than 5. If the difference is greater than 5, we print “The difference is greater than 5”. If the difference is less than or equal to 5, we print “The difference is less than or equal to 5”. If the “x” variable is not greater than the “y” variable, we print “The second number is greater than or equal to the first number”. Since the “x” variable is 10 and the “y” variable is 5 in this example, the difference is greater than 5, so the output will be “The difference is greater than 5”.
x = 5
y = 10
message = “x is less than y” if x < y else “x is greater than or equal to y”
print(message)
Output: x is less than y
Explanation: In this example, we use the “if…else” statement with a ternary operator. Instead of writing a full “if…else” block, we use the ternary operator to assign the result to a variable. If the condition “x < y” is True, we assign the message “x is less than y” to the variable. If the condition is False, we assign the message “x is greater than or equal to y” to the variable. Since the “x” variable is 5 and the “y” variable is 10 in this example, the condition is True, so the output will be “x is less than y”.
Example 17: If…Else with List Comprehension
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
odd_numbers = [num for num in numbers if num % 2 != 0]
print("Even numbers:", even_numbers)
print("Odd numbers:", odd_numbers)
Output:
Even numbers: [2, 4, 6, 8, 10]
Odd numbers: [1, 3, 5, 7, 9]
Explanation: In this example, we use the “if…else” statement with list comprehension. We first create a list of numbers from 1 to 10. We then use list comprehension to create two new lists: one with even numbers and one with odd numbers. We check if each number in the “numbers” list is even or odd using the modulus operator. If the number is even (i.e., the modulus is 0), we add it to the “even_numbers” list. If the number is odd (i.e., the modulus is not 0), we add it to the “odd_numbers” list. We then print both lists. The output shows that the “even_numbers” list contains the even numbers from 1 to 10, while the “odd_numbers” list contains the odd numbers from 1 to 10.
user = {"name": "John", "age": 30, "country": "USA"}
if "age" in user:
print(f"{user['name']} is {user['age']} years old")
else:
print("Age information not available")
Output: John is 30 years old
Explanation: In this example, we use the “if…else” statement with dictionaries. We first create a dictionary “user” with three key-value pairs: “name”, “age”, and “country”. We then check if the key “age” is in the dictionary using the “in” keyword. If it is, we print a message that includes the user’s name and age. If it is not, we print a message that says “Age information not available”. Since the “age” key is in the dictionary in this example, the output will be “John is 30 years old”.
x = 10
if x > 10:
print("x is greater than 10")
elif x < 10:
print("x is less than 10")
else:
print("x is equal to 10")
Output: x is equal to 10
Explanation: In this example, we use the “if…else” statement with multiple conditions. We first assign a value of 10 to the variable “x”. We then check if “x” is greater than 10 using the “if” statement. If it is, we print a message that says “x is greater than 10”. If the “if” statement is False, we move on to the “elif” statement and check if “x” is less than 10. If it is, we print a message that says “x is less than 10”. If the “elif” statement is also False, we move on to the “else” statement and print a message that says “x is equal to 10”. Since the value of “x” is 10 in this example, the output will be “x is equal to 10”.
x = 5
if x > 0:
print("Positive number")
print("Greater than zero")
else:
print("Non-positive number")
print("Less than or equal to zero")