Skip to content
Home » Posts » How to write if in Python

How to write if in Python

  • by
  1. Setting a Variable:
   # Set a variable
   x = 10

Here, we’re creating a variable named x and assigning it the value 10.

  1. Using if, elif, and else Statements:
   # Check conditions using if, elif, and else
   if x > 5:
       # Code to execute if the condition is True
       print("x is greater than 5")
   elif x == 5:
       # Code to execute if another_condition is True
       print("x is equal to 5")
   else:
       # Code to execute if none of the above conditions are True
       print("x is less than 5")
  • The if statement checks if x is greater than 5. If it’s true, it executes the indented code block under if.
  • The elif statement (short for “else if”) checks if x is equal to 5. If the previous condition (in if) is not true, it checks this condition. If true, it executes the indented code block under elif.
  • The else statement provides a code block that will be executed if none of the previous conditions are true.
  1. Executing the Code:
    When you run this Python script, it will print “x is greater than 5” because the value of x (10) is indeed greater than 5.
  2. Indentation:
    In Python, indentation is crucial. The lines of code within the if, elif, and else blocks are indented to indicate that they are part of those blocks. Incorrect indentation can lead to syntax errors.
  3. Logical Operators:
    You can use logical operators (and, or, not) to combine multiple conditions. For example:
   age = 25

   if age >= 18 and age <= 30:
       print("You are between 18 and 30 years old")

This checks if age is both greater than or equal to 18 and less than or equal to 30.

Remember, this is a basic example. As you become more familiar with Python, you’ll encounter more complex uses of if statements and conditions. Practice and experimentation are key to mastering conditional statements in Python!

Image by Gerd Altmann from Pixabay