If Else Statement In Python

9th February 2026 by Tanishq Chavan
Python C C++ Javascript React JS
Python Programming Language

Python If...Else Statements: Control Your Code

Python supports the usual logical conditions from mathematics. These conditions can be used in several ways, most commonly in "if statements" and loops.


An "if statement" is written by using the if keyword.

a = 33
b = 200
if b > a:
  print("b is greater than a")

[!IMPORTANT] Indentation is everything! Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other languages often use curly brackets {}.


The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition".

a = 33
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")

The else keyword catches anything which isn't caught by the preceding conditions.

a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

4. Logical Operators in Conditions

You can combine multiple conditions using and, or, and not.

| Operator | Description | Example | | :--- | :--- | :--- | | and | True if both conditions are true | if a > b and c > a: | | or | True if at least one is true | if a > b or a > c: | | not | Reverses the result | if not a > b: |


5. Short Hand (One Line)

If you have only one statement to execute, you can put it on the same line as the if statement.

Short Hand If:

if a > b: print("a is greater than b")

Short Hand If...Else (Ternary Operator):

print("A") if a > b else print("B")

6. Nested If

You can have if statements inside if statements, this is called nested if statements.

x = 41

if x > 10:
  print("Above ten,")
  if x > 20:
    print("and also above 20!")
  else:
    print("but not above 20.")

if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.

a = 33
b = 200

if b > a:
  pass

How did you feel about this post?

๐Ÿ˜ ๐Ÿ™‚ ๐Ÿ˜ ๐Ÿ˜• ๐Ÿ˜ก

Was this helpful?

๐Ÿ‘ ๐Ÿ‘Ž