🔛 Conditional Statements¶
1. If Statement¶
The if statement is used to test a specific condition. If the condition is true, a block of indented code will be executed.
In [1]:
Copied!
x = 10
if x > 0:
print("x is positive") # prints: x is positive
x = 10
if x > 0:
print("x is positive") # prints: x is positive
x is positive
In this example, the code within the if statement will execute because the condition (x > 0) is true.
2. Else Statement¶
The else statement is used to define a block of code to be executed if the associated if statement's condition is false.
In [2]:
Copied!
x = -10
if x > 0:
print("x is positive")
else:
print("x is not positive") # prints: x is not positive
x = -10
if x > 0:
print("x is positive")
else:
print("x is not positive") # prints: x is not positive
x is not positive
3. Elif Statement¶
The elif (short for else if) statement is used to specify multiple conditions. If the condition for if is False, it checks the condition of the next elif block and so on. If all the conditions are False, the body of else is executed.
In [3]:
Copied!
x = 0
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero") # prints: x is zero
else:
print("x is negative")
x = 0
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero") # prints: x is zero
else:
print("x is negative")
x is zero