In Python, conditional statements are used for decision-making in your code. The primary conditional statements in Python are if
, else
, and elif
. These statements allow you to execute different blocks of code based on certain conditions.
The if
statement
The if
statement is the most basic form of decision-making in Python. It evaluates a test expression and executes a block of code if the expression is True
.
x = 1
if x > 0:
print(x, "is a positive number")
# output: 1 is a positive number
Note:
Indentation is crucial in Python. All statements within the if
block must be indented.
Example with code outside if
block:
x = 1
if x > 0:
print(x, "is a positive number")
print('Outside of if condition')
# output:
# 1 is a positive number
# Outside of if condition
The if...else
statement
The if...else
statement adds an alternative block of code to execute if the test expression is False
.
x = 1
if x >= 0:
print(x, "is a positive number")
else:
print(x, "is a negative number")
print('End of if...else...')
# output:
# 1 is a positive number
# End of if...else...
The if...elif...else
statement
The if...elif...else
statement allows you to check multiple expressions for True
and execute a block of code as soon as one of the conditions is True
. If none of the conditions are True
, the else
block is executed.
x = -5
if x == 0:
print(x, "is zero")
elif x > 0:
print(x, "is positive")
else:
print(x, "is negative")
print('End of if statement')
# output :
# -5 is negative
# End of if statement
Nested if
statements
You can nest if
statements within other if
statements to create more complex decision-making structures.
x = 8
if x == 0:
print(x, "is zero")
elif x > 0:
if x == 10:
print(x, "is equal to 10")
elif x > 10:
print(x, "is greater than 10")
else:
print(x, "is less than 10")
else:
print(x, "is negative")
print('End of if statement')
# output :
# 8 is less than 10
# End of if statement
Conclusion
Understanding and effectively using if
, else
, and elif
statements is essential for controlling the flow of your Python programs. These conditional statements allow you to execute different code blocks based on various conditions, making your programs more dynamic and capable of handling different situations. If you encounter any issues, please get in touch with our support. Happy coding in Deepnote!