Python Conditions and If statements
In Python Conditions , the if statement is used for conditional execution. It allows you to execute a block of code only when a specific condition is met. Let’s explore the if, if…else, and if…elif…else statements:
if Statement: –
The basic syntax of an if statement is as follows:
if condition:
# Code to execute if the condition is True
For Example,
number = 10
if number > 0:
print ('Number is positive')
if…else Statement
The if…else statement allows you to execute different code blocks based on whether the condition is True or False.
Syntax:
if condition:
# Code to execute if the condition is True
else:
# Code to execute if the condition is False
For Example,
number = 10
if number > 0:
print ('Positive number')
else:
print ('Negative number')
if…elif…else Statement
When you have multiple conditions to check, you can use the if…elif…else statement.
Syntax: –
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
else:
# Code to execute if none of the conditions are True
For Example: –
number = 10
if number > 0:
print ('Positive number')
elif number == 0:
print('Zero')
else:
print ('Negative number')
Using AND Operator
The and keyword is a logical operator, and is used to combine conditional statements:
For Example
Test if x
is greater than y
, AND if z
is greater than x
:
x = 20
y = 3
x = 50
if x > y and z > x:
print("Both conditions are True")
Using OR Operator
The OR
keyword is a logical operator, and is used to combine conditional statements:
For Example,
Test if x
is greater than y
, OR if x
is greater than z
:
x = 20
y = 3
x = 50
if x > y or x > z:
print("At least one of the conditions is True")
Using Not in Python
The not
keyword is a logical operator, and is used to reverse the result of the conditional statement:
For Example,
Test if x
is NOT greater than y
:
x= 33
y= 200
if not x > y:
print("x is NOT greater than y")
Using Nested If
You can have if
statements inside if
statements, this is called nested if
statements.
For Example,
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print ("and also above 20!")
else:
print ("but not above 20.")