if-else Statement
In Python, the if-else statement allows you to execute different blocks of code based on whether a specified condition is true or false. The basic syntax is as follows:
if condition:
# Code to be executed if the condition is True
else:
# Code to be executed if the condition is False
Here's a more detailed breakdown:
- The
ifkeyword is followed by a condition that evaluates to eitherTrueorFalse. - If the condition is
True, the indented code block following theifstatement is executed. - If the condition is
False, the indented code block following theelsestatement is 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 x is greater than 5, the first print statement is executed; otherwise, the print statement in the else block is executed.
Nested if-else Statements:
You can also nest if-else statements to handle more complex conditions:
x = 10
if x > 5:
print("x is greater than 5")
else:
if x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
In this example, the first if statement checks if x is greater than 5. If it is, the first print statement is executed. If it's not, the nested else statement checks if x is equal to 5, and if so, the second print statement is executed. If neither condition is met, the print statement in the second else block is executed.
Example with User Input:
user_input = input("Enter a number: ")
number = int(user_input)
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
In this example, the program takes user input, converts it to an integer, and then checks whether the number is even or odd using an if-else statement.
The if-else statement is fundamental for controlling the flow of your program based on conditions. It allows you to handle different scenarios based on whether a condition is true or false.