Skip to main content

Conditionals

Python allows us to compare values using comparison operators, enabling us to make decisions based on these comparisons. This is fundamental for controlling the flow of a program.

Boolean Data Type

The result of a comparison is a Boolean value: either True or False. Booleans represent one of two possible states.

Comparison Operators

Python provides several comparison operators:

OperatorNameDescription
==Equal toChecks if two values are equal
!=Not equal toChecks if two values are not equal
>Greater thanChecks if the left value is greater than the right value
<Less thanChecks if the left value is less than the right value
>=Greater than or equal toChecks if the left value is greater than or equal to the right value
<=Less than or equal toChecks if the left value is less than or equal to the right value

Examples with Numbers

print(10 > 1)        # True
print(3 == 5) # False
print(7 != 2) # True
print(5 >= 5) # True
print(4 < 8) # True
print(9 <= 3) # False

Note: Comparison operators return Boolean values (True or False).

Equality vs. Assignment

Be careful not to confuse the equality operator == with the assignment operator =.

a = 5       # Assignment: sets the value of a to 5
print(a == 5) # Equality check: True

Comparing Different Data Types

Comparing incompatible data types (e.g., an integer and a string) can result in a TypeError.

print(1 < "1")  # TypeError: '<' not supported between instances of 'int' and 'str'

However, equality == and inequality != comparisons between different data types are valid but usually return False.

print(1 == "1")  # False
print(1 != "1") # True

Comparing Strings

Comparison operators can also be used with strings, comparing their lexicographical order based on Unicode values.

CharacterUnicode Value
'A'65
'B'66
......
'a'97
'b'98
......

Examples with Strings

print("apple" == "apple")   # True
print("apple" != "banana") # True
print("cat" > "bat") # True
print("Dog" < "dog") # True
print("Zebra" < "apple") # True

Note: Uppercase letters have lower Unicode values than lowercase letters.

Logical Operators

Logical operators allow us to build complex boolean expressions by combining simpler ones.

Operators

  • and: True if both operands are True.
  • or: True if at least one operand is True.
  • not: Inverts the Boolean value.

and Operator

print((5 > 1) and (5 < 10))    # True and True => True
print((5 > 10) and (5 < 10)) # False and True => False

or Operator

print((5 > 10) or (5 < 10))    # False or True => True
print((5 > 10) or (5 == 10)) # False or False => False

not Operator

print(not (5 > 1))   # not True => False
print(not (5 > 10)) # not False => True

Control Flow with Conditional Statements

Conditional statements allow us to control the flow of execution based on certain conditions.

if Statements

An if statement executes a block of code if its condition evaluates to True.

if condition:
# Code to execute if condition is True

Example

username = "jsmith"

if len(username) < 3:
print("Invalid username: Must be at least 3 characters long.")

else Statements

An else statement can follow an if statement and executes if the if condition is False.

if condition:
# Code if condition is True
else:
# Code if condition is False

Example

if len(username) < 3:
print("Invalid username: Must be at least 3 characters long.")
else:
print("Username is valid.")

The Modulo Operator %

The modulo operator % returns the remainder of the division between two numbers.

print(5 % 2)   # Output: 1
print(10 % 5) # Output: 0

Checking for Even or Odd Numbers

def is_even(number):
if number % 2 == 0:
return True
else:
return False

print(is_even(4)) # True
print(is_even(7)) # False

Simplified Version:

def is_even(number):
return number % 2 == 0

elif Statements

An elif (else if) statement allows us to check multiple conditions sequentially.

if condition1:
# Code if condition1 is True
elif condition2:
# Code if condition2 is True
else:
# Code if none of the above conditions are True

Example: Username Validation

if len(username) < 3:
print("Invalid username: Must be at least 3 characters long.")
elif len(username) > 15:
print("Invalid username: Must be at most 15 characters long.")
elif not username.isalpha():
print("Invalid username: Must contain only letters.")
else:
print("Username is valid.")

Note: Conditions are evaluated in order. Once a condition is True, the corresponding block executes, and the rest are skipped.

Key Takeaways

  • Comparison Operators allow comparison of values, resulting in a Boolean (True or False).
  • Logical Operators (and, or, not) enable the creation of complex logical expressions.
  • Conditional Statements (if, elif, else) control the flow of a program based on conditions.
  • Modulo Operator % is useful for determining divisibility and checking for even or odd numbers.