The if-else
statement in Python is used for control flow in your program. It allows you to specify two blocks of code, one to be executed if a certain condition is met, and another to be executed if the condition is not met.
The basic syntax for an if-else
statement is:
if condition:
# code to execute if condition is True
else:
# code to execute if condition is False
The condition
is a boolean expression that evaluates to either True
or False
. If the condition is True
, the code inside the first block (after the if
keyword) is executed. If the condition is False
, the code inside the second block (after the else
keyword) is executed.
Here’s an example of an if-else
statement in Python:
x = 3
if x > 5:
print(“x is greater than 5”)
else:
print(“x is not greater than 5”)
In this example, the condition x > 5
is False
, so the code inside the else
block print("x is not greater than 5")
is executed and the output is x is not greater than 5
.
In summary, the if-else
statement in Python allows you to control the flow of your program by executing different blocks of code based on whether a specified condition is met or not.
Disclaimer: The information provided on the blog is for educational and informational purposes only. It should not be considered as a substitute for professional advice.
Leave a Reply