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
Operator | Meaning | Example | Result |
---|---|---|---|
== | Equal to | a == b | True if a equals b |
!= | Not equal to | a != b | True if a not equals b |
< | Less than | a < b | True if a smaller than b |
<= | Less than or equal to | a <= b | True if a ≤ b |
> | Greater than | a > b | True if a greater than b |
>= | Greater than or equal to | a >= b | True 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
Operator | Description | Example |
---|---|---|
+ | Addition | x + y |
- | Subtraction | x - y |
* | Multiplication | x * y |
/ | Division | x / y |
% | Modulus (remainder) | x % y |
** | Exponent (power) | x ** y |
// | Floor division | x // y |
Assignment Operators
Operator | Example | Equivalent To |
---|---|---|
= | x = 5 | Assigns value |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
%= | x %= 3 | x = x % 3 |
//= | x //= 3 | x = x // 3 |
**= | x **= 3 | x = x ** 3 |
Logical Operators
Operator | Description | Example | Result |
---|---|---|---|
and | True if both are True | x < 5 and x < 10 | True |
or | True if any one is True | x < 5 or x < 4 | True |
not | Reverses result | not(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.