if Statement


☞ It is used to execute a block of code only if a specified condition is true.

Syntax :
 
if <test_condition>:
    Statement_1
    Statement_2
    ……….
Example :
 
x = int(input("Enter a number : "))
if x>0:
    print("Positive Number")
if x<0:
    print("Negative Number")
if x==0:
    print("Neither Positive Nor Negative")
Output :
 
Enter a number : -6
Negative Number
Explanation :
  • If the user inputs a positive number, only the first if statement will evaluate to true, and "Positive Number" will be printed.
  • If the user inputs a negative number, only the second if statement will evaluate to true, and "Negative Number" will be printed.
  • If the user inputs 0, only the third if statement will evaluate to true, and "Neither Positive Nor Negative" will be printed.
  • If the user inputs any other value, none of the if statements will evaluate to true, and no message will be printed.
One thing to note is that these conditions are mutually exclusive, meaning only one of the if blocks will execute based on the value of x. If you want to make sure only one message is printed regardless of the value of x, you should use elif and else statements instead of separate if statements.