Python - if Statement


In Python, the if statement is used to execute a block of code only if a specified condition is true. It's part of conditional statements that allow decision-making in code.

Syntax


 

if condition:
    # code to execute if the condition is true

Example


 

x = 10

if x > 5:
    print("x is greater than 5")
 

Explanation

  • if: This keyword introduces the condition.
  • condition: This is a logical statement that evaluates to True or False.
  • :: A colon follows the condition.
  • Indentation: The code block that follows must be indented.

Adding else

You can add an else statement to handle cases where the condition is not true:


 

x = 3

if x > 5:
    print("x is greater than 5")
else:
    print("x is less than or equal to 5")
 

Using elif for Multiple Conditions

The elif keyword allows testing multiple conditions:


 

x = 5

if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is equal to 5")
else:
    print("x is less than 5")
 

Logical Conditions

You can use comparison operators (e.g., >, <, ==, etc.) and logical operators (e.g., and, or, not).

Example using and:


 

x = 7
if x > 5 and x < 10:
    print("x is between 5 and 10")

Let me know if you'd like more details on conditions or operators!




Rs. 5.0 Rs. 10.0


Buy Now