Conditions in Python

Programming Fundamentals October 15, 2025

Conditions in Python


What are Conditions?

  • Conditions help make decisions in code.
  • They compare values and return True or False.

Common Comparison Operators

OperatorMeaningExampleResult
==Equal toa == bTrue if a equals b
!=Not equal toa != bTrue if a not equals b
<Less thana < bTrue if a smaller than b
<=Less than or equal toa <= bTrue if a ≤ b
>Greater thana > bTrue if a greater than b
>=Greater than or equal toa >= bTrue if a ≥ b

If Statements in Python

1. Simple If Statement

if condition:
    # code block

Executes only if condition is True. If False, nothing happens.

Example:

firstval = 630
secondval = 440
if firstval > secondval:
    print(f"{firstval} is greater than {secondval}")

2. If-Else Statement

Used when you want one of two possible outcomes.

if condition:
    # code if True
else:
    # code if False

Example:

firstval = 1300
secondval = 440

if firstval > secondval:
    print(f"{firstval} is greater than {secondval}")
else:
    print(f"{firstval} is less than {secondval}")

3. Elif Statement

Used for multiple conditions (like “else if” in other languages).

if condition1:
    # code
elif condition2:
    # code
else:
    # code

Example:

firstval = 440
secondval = 440

if firstval > secondval:
    print("firstval is greater")
elif firstval < secondval:
    print("firstval is smaller")
elif firstval == secondval:
    print("Both are equal")

Note: else is optional with elif.


Arithmetic Operators

OperatorDescriptionExample
+Additionx + y
-Subtractionx - y
*Multiplicationx * y
/Divisionx / y
%Modulus (remainder)x % y
**Exponent (power)x ** y
//Floor divisionx // y

Assignment Operators

OperatorExampleEquivalent To
=x = 5Assigns value
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
%=x %= 3x = x % 3
//=x //= 3x = x // 3
**=x **= 3x = x ** 3

Logical Operators

OperatorDescriptionExampleResult
andTrue if both are Truex < 5 and x < 10True
orTrue if any one is Truex < 5 or x < 4True
notReverses resultnot(x < 5)False

Quick Tips

  • Indentation is mandatory in Python.
  • Always test multiple conditions with elif.
  • Use logical operators to combine multiple conditions.
  • if statements are used inside loops for decision-making.