Python, the if...else statement is used to make decisions based on certain conditions. It allows the program to execute different blocks of code depending on whether a condition evaluates to True or False. The basic syntax of the if...else statement is as follows:
if condition:
# code block to execute if the condition is True
else:
# code block to execute if the condition is False
Here's how it works:
The condition is an expression that evaluates to either True or False.
If the condition is True, the code block under the if statement will be executed.
If the condition is False, the code block under the else statement will be executed.
Example:
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
In this example, if the value of x is greater than 5, the program will print "x is greater than 5"; otherwise, it will print "x is not greater than 5".
You can also use multiple elif (short for "else if") statements to test multiple conditions in sequence. The elif statements are checked one by one until a condition evaluates to True, and the corresponding code block is executed. The else block will be executed only if none of the previous conditions are True.
Example with elif:
x = 7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but not greater than 10")
else:
print("x is not greater than 5")
In this example, if the value of x is greater than 10, it will print "x is greater than 10". If x is not greater than 10 but greater than 5, it will print "x is greater than 5 but not greater than 10". Otherwise, it will print "x is not greater than 5".
examples of if...else statements in Python:
num = 10
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a leap year")
else:
print(year, "is not a leap year")
num = 7
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")
a = 10
b = 20
c = 15
if a >= b and a >= c:
print(a, "is the largest")
elif b >= a and b >= c:
print(b, "is the largest")
else:
print(c, "is the largest")
word = "radar"
if word == word[::-1]:
print(word, "is a palindrome")
else:
print(word, "is not a palindrome")
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
These examples showcase different use cases of the if...else statement, demonstrating how it can be used to control the flow of a program based on various conditions.