When we want to execute a code only if a certain criteria is fulfilled, decision making is needed. For decision making in Python if…else statement is used.
Python IF Statement –
The statements in the ‘if’ block will run only if the condition(s) is/are True. All non-zero integers are treated as True and ‘0’ & ‘None’ values are treated as False.
number = 3
if number > 0 :
print("Number is Positive")
if number < 0:
print("Number is Negative")
Output:
Number is Positive
Python if…else Statement –
The statements in the ‘if’ block will run only if the condition(s) is/are True, otherwise the statement(s) in the else block will be executed. All non-zero integers are treated as True and ‘0’ & ‘None’ values are treated as False.
number = 3
if number // 2 :
print("Number is Even")
else:
print("Number is Odd")
Output:
Number is Odd
Python if…elif…else Statement –
If we have to make decision based on multiple conditions we make use of if…elif…else statements
The statements in the ‘if’ and ‘elif’ block will run only if the condition(s) is/are True,otherwise the statement(s) in the else block will be executed. All non-zero integers are treated as True and ‘0’ & ‘None’ values are treated as False.
Syntax
if condition:
statement(s) elif condition: statement(s) else: statement(s)
Login/Signup to comment