Here are some key points to keep in mind about if … else statements in Python:
An if … else statement is used to control the flow of a program based on a particular condition.
The if … else statement consists of an if statement followed by an optional else statement. If the condition in the if statement evaluates to True, the code inside the if block is executed. Otherwise, the code inside the else block is executed.
The if … else statement can also be combined with the elif keyword to add additional conditions. The elif keyword is short for “else if” and is used to test multiple conditions.
The syntax for an if … else statement is as follows:
if condition:
# Code to execute if condition is True
else:
# Code to execute if condition is False
The code inside the if block and the else block should be indented with four spaces to indicate that they belong to the same block.
The condition in the if statement can be any expression that returns a Boolean value (True or False). This can be a simple comparison, such as x == y
, or a more complex expression involving logical operators, such as x < y and z > y
.
It is important to make sure that the condition in the if statement is properly formatted and evaluates to the correct value. Otherwise, the wrong code may be executed.
The if … else statement can be nested inside other if statements to create more complex conditions.
Finally, the if … else statement can also be used in conjunction with other programming constructs, such as loops and functions, to create more advanced programs.
age = int(input("Enter your age: "))
if age < 18:
print("You are not eligible to vote")
else:
print("You are eligible to vote")
Output:
Enter your age: 20
You are eligible to vote
Explanation: In this example, we use the “if…else” statement with user input. We first ask the user to enter their age using the “input” function, and we convert the input to an integer using the “int” function. We then check if the age is less than 18 using the “if” statement. If it is, we print a message that says “You are not eligible to vote”. If the “if” statement is False, we move on to the “else” statement and print a message that says “You are eligible to vote”. If the user enters an age of 20, for example, the output will be “You are eligible to vote”.
x = 5
if x > 0:
if x % 2 == 0:
print("x is a positive even number")
else:
print("x is a positive odd number")
else:
print("x is non-positive")
Output: x is a positive odd number
Explanation: In this example, we use nested “if…else” statements to check if “x” is a positive even or odd number. We first assign a value of 5 to the variable “x”. We then check if “x” is greater than 0 using the outer “if” statement. If it is, we move on to the inner “if” statement and check if “x” is divisible by 2 using the modulo operator. If it is, we print a message that says “x is a positive even number”. If the inner “if” statement is False, we move on to the inner “else” statement and print a message that says “x is a positive odd number”. If the outer “if” statement is False, we print a message that says “x is non-positive”. Since the value of “x” is 5 in this example, the output will be “x is a positive odd number”.
x = 5
message = “x is positive” if x > 0 else “x is non-positive”
print(message)
Output: x is positive
Explanation: In this example, we use the ternary operator to assign a value to the variable “message” based on the condition of “x” being greater than 0 or not. We first assign a value of 5 to the variable “x”. We then use the ternary operator to check if “x” is greater than 0. If it is, we assign the string “x is positive” to the variable “message”. If it is False, we assign the string “x is non-positive” to the variable “message”. We then print the value of the variable “message”. Since the value of “x” is 5 in this example, the output will be “x is positive”.
numbers = [1, 2, 3, 4, 5]
result = [x if x > 2 else 0 for x in numbers]
print(result)
Output: [0, 0, 3, 4, 5]
Explanation: In this example, we use the “if…else” statement with list comprehension to create a new list “result” that contains the numbers greater than 2 from the list “numbers” and replaces the numbers less than or equal to 2 with 0. We first define a list of numbers [1, 2, 3, 4, 5]. We then use list comprehension to loop through each number in the list “numbers” and check if it is greater than 2 using the “if” statement. If it is, we include the number in the new list “result”. If it is False, we replace the number with 0 using the “else” statement. We then print the new list “result”. The output will be [0, 0, 3, 4, 5]
.
x = 5
y = 10
if x > 0 and y > 0:
print("Both x and y are positive")
elif x < 0 and y < 0:
print("Both x and y are negative")
elif x > 0 and y < 0:
print("x is positive and y is negative")
else:
print("x is negative and y is positive")
Output: x is positive and y is negative
Explanation: In this example, we use the “if…else” statement with multiple conditions to determine the relationship between two variables “x” and “y”. We first assign the values of 5 and 10 to the variables “x” and “y”, respectively. We then use the “and” operator to check if both “x” and “y” are positive using the first “if” statement. If it is True, we print a message that says “Both x and y are positive”. If it is False, we move on to the next “elif” statement and check if both “x” and “y” are negative. If it is True, we print a message that says “Both x and y are negative”. If it is False, we move on to the next “elif” statement and check if “x” is positive and “y” is negative. If it is True, we print a message that says “x is positive and y is negative”. If all the above conditions are False, we print a message that says “x is negative and y is positive”. Since the values of “x” and “y” are 5 and 10, respectively, the output will be “x is positive and y is negative”.
try:
x = int(input("Enter a number: "))
result = 100 / x
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result is", result)
Output:
Case 1:
Enter a number: 10
Result is 10.0
Case 2:
Enter a number: 0
Cannot divide by zero
Explanation: In this example, we use the “if…else” statement with exception handling to catch and handle different types of errors that may occur while executing a piece of code. We first use the “try” block to take input from the user and divide the number by 100. If the user inputs a non-integer value, a “ValueError” is raised, and the program prints “Invalid input” using the first “except” block. If the user inputs 0 as the value of “x”, a “ZeroDivisionError” is raised, and the program prints “Cannot divide by zero” using the second “except” block. If no error is raised, the program executes the “else” block and prints the result of the division. In the first case, since the user inputs 10, the output will be “Result is 10.0”. In the second case, since the user inputs 0, the output will be “Cannot divide by zero”.
result = (lambda x: x**2 if x % 2 == 0 else x**3)(5)
print(result)
Output: 125
numbers = [1, 2, 3, 4, 5, 6]
squares = [num**2 if num % 2 == 0 else num**3 for num in numbers]
print(squares)
Output: [1, 4, 27, 16, 125, 36]
Explanation: In this example, we use the “if…else” statement with a list comprehension to generate a new list of squares of even numbers and cubes of odd numbers. We first define a list of numbers from 1 to 6. We then use the list comprehension to iterate over each number in the list and generate a new list of squares of even numbers and cubes of odd numbers based on the condition specified in the “if…else” statement. Since 1, 3, and 5 are odd numbers, their cubes are generated and added to the new list, while 2, 4, and 6 are even numbers, their squares are generated and added to the new list. The output will be [1, 4, 27, 16, 125, 36]
.
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
Output: 120
Explanation: In this example, we use the “if…else” statement with recursion to calculate the factorial of a number. We define a function “factorial” that takes an argument “n”. If “n” is equal to 1, we return 1, which is the base case. If “n” is greater than 1, we recursively call the “factorial” function with “n-1” as the argument and multiply the result with “n” to get the factorial of “n”. The output will be the factorial of 5, which is 120.
x = 5
y = 10
z = 20
if x < y and y < z:
print("x is less than y and y is less than z")
else:
print("x is not less than y or y is not less than z")
Output: x is less than y and y is less than z
Explanation: In this example, we use the “if…else” statement with boolean operators to check if “x” is less than “y” and “y” is less than “z”. We first assign the values of 5, 10, and 20 to the variables “x”, “y”, and “z”, respectively. We then use the “and” operator to check if both conditions are True. If it is True, we print a message that says “x is less than y and y is less than z”. If it is False, we move on to the “else” statement and print a message that says “x is not less than y or y is not less than z”. Since the values of “x”, “y”, and “z” are 5, 10, and 20, respectively, the output will be “x is less than y and y is less than z”.
employee = {"name": "John", "age": 30, "salary": 50000}
if employee.get("salary") > 60000:
print("Employee is highly paid")
else:
print("Employee is not highly paid")
Output: Employee is not highly paid
Explanation: In this example, we use the “if…else” statement with dictionaries to check if an employee is highly paid or not. We define a dictionary “employee” that contains the name, age, and salary of an employee. We then use the “get” method of the dictionary to retrieve the value of the “salary” key. If the salary is greater than 60000, we print a message that says “Employee is highly paid”. If it is not, we move on to the “else” statement and print a message that says “Employee is not highly paid”. Since the value of the “salary” key in the “employee” dictionary is 50000, the output will be “Employee is not highly paid”.
square = lambda x: x**2 if x % 2 == 0 else x**3
print(square(2))
print(square(3))
Output:
4
27
Explanation: In this example, we use the “if…else” statement with lambda functions to generate the square of even numbers and cube of odd numbers. We define a lambda function “square” that takes an argument “x”. If “x” is an even number, it returns the square of “x”. If “x” is an odd number, it returns the cube of “x”. We then call the “square” function with arguments 2 and 3 and print the output. The output will be 4 and 27, respectively.
file = open("test.txt", "r")
if "Python" in file.read():
print("Python is present in the file")
else:
print("Python is not present in the file")
file.close()
Output: Python is present in the file
Explanation: In this example, we use the “if…else” statement with file I/O to check if a file contains the word “Python” or not. We first open a file “test.txt” in read mode using the “open” function. We then use the “read” method of the file object to read the contents of the file and check if the word “Python” is present in it using the “in” keyword. If the word “Python” is present, we print a message that says “Python is present in the file”. If it is not present, we move on to the “else” statement and print a message that says “Python is not present in the file”. Since the file “test.txt” contains the word “Python”, the output will be “Python is present in the file”. Finally, we close the file using the “close” method of the file object.
numbers = [1, 2, 3, 4, 5]
new_numbers = [x**2 if x % 2 == 0 else x**3 for x in numbers]
print(new_numbers)
Output: [1, 4, 27, 16, 125]
Explanation: In this example, we use the “if…else” statement with list comprehension to generate a new list that contains the square of even numbers and cube of odd numbers from an existing list. We define a list “numbers” that contains the integers from 1 to 5. We then use list comprehension to create a new list “new_numbers” that contains the square of even numbers and cube of odd numbers from the “numbers” list. We use the “if…else” statement in the list comprehension to check if a number is even or odd. If a number is even, we return its square, otherwise, we return its cube. Finally, we print the new list “new_numbers”. The output will be [1, 4, 27, 16, 125]
.
try:
a = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero")
else:
print("Result: ", a)
Output: Error: Division by zero
Explanation: In this example, we use the “if…else” statement with exception handling to handle the “ZeroDivisionError” exception that occurs when we divide a number by zero. We use the “try…except” block to catch the exception. If the exception occurs, we move on to the “except” block and print a message that says “Error: Division by zero”. If the exception does not occur, we move on to the “else” block and print the result of the division operation. Since we are dividing a number by zero, the “ZeroDivisionError” exception will occur, and the output will be “Error: Division by zero”.
a = 5
b = 10
if a > 0 and b > 0:
print("Both a and b are positive")
else:
print("Either a or b is negative")
Output: Both a and b are positive
Explanation: In this example, we use the “if…else” statement with boolean operators to check if two numbers are positive or not. We define two variables “a” and “b” and assign them the values 5 and 10, respectively. We use the “and” operator to check if both “a” and “b” are greater than zero. If both are greater than zero, we print a message that says “Both a and b are positive”. If either of them is negative, we move on to the “else” block and print a message that says “Either a or b is negative”. Since both “a” and “b” are greater than zero, the output will be “Both a and b are positive”.
person = {
"name": "John",
"age": 30,
"gender": "male"
}
if "age" in person:
print("Person's age is:", person["age"])
else:
print("Age not found")
Output: Person's age is: 30
Explanation: In this example, we use the “if…else” statement to check if a key “age” exists in a dictionary “person”. We define a dictionary “person” that contains the person’s name, age, and gender. We use the “in” operator to check if the key “age” exists in the dictionary “person”. If it exists, we print a message that says “Person’s age is:” followed by the value of the key “age”. If it does not exist, we move on to the “else” block and print a message that says “Age not found”. Since the key “age” exists in the dictionary “person”, the output will be “Person’s age is: 30”.
x = 15
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10")
else:
print("x is less than or equal to 5")
Output: x is greater than 10
Explanation: In this example, we use the “if…else” statement with multiple conditions to check the value of a variable “x”. We assign the value 15 to “x”. We use the “if” statement to check if “x” is greater than 10. If it is, we print a message that says “x is greater than 10”. If it is not, we move on to the “elif” block and check if “x” is greater than 5. If it is, we print a message that says “x is greater than 5 but less than or equal to 10”. If neither of the conditions is true, we move on to the “else” block and print a message that says “x is less than or equal to 5”. Since “x” is greater than 10, the output will be “x is greater than 10”.
name = "John"
age = 30
result = "My name is {0} and I am {1} years old".format(name, age)
if age > 18:
result += " and I am an adult"
else:
result += " and I am a minor"
print(result)
Output: My name is John and I am 30 years old and I am an adult
Explanation: In this example, we use the “if…else” statement with string formatting to create a string that includes information about a person’s name, age, and status (adult or minor). We define two variables “name” and “age” and assign them the values “John” and 30, respectively. We use the “format” method to create a string “result” that includes the values of “name” and “age”. We then use the “if…else” statement to check if the person is an adult or a minor. If the age is greater than 18, we append the string ” and I am an adult” to the “result” string. If the age is less than or equal to 18,