Python if-else and conditional expressions

  • Post category:python
  • Reading time:12 mins read

Python If-Else

In our last post, we talked about the concept of Python Dictionary. In this post we will understand Python if-else construct and conditional expressions. The if-else statement in Python is used for decision-making. It allows you to execute certain code if a condition is true and another set of code if the condition is false. Here’s the basic syntax:

if condition:
       # Code block to execute if condition is true
else:
       # Code block to execute if condition is false

Here is a simple example:

count = 100

if count > 100:
    print("Count is greater than 100.")
else:
    print("Count is not greater than 100.")

# Output
Count is not greater than 100.

You can also have multiple conditions using elif (short for “else if”):

count = 100

if count > 100:
    print("Count is greater than 100.")
elif count == 100:
    print("Count is equal to 100.")
else:
    print("Count is less than 100.")

# Output
Count is equal to 100.

Python conditional expressions

In Python, conditions are expressions that evaluate to either True or False. These conditions are commonly used in control flow statements like if, elif, and while loops to make decisions about which blocks of code to execute. Here are some common types of conditions in Python:

Comparison Operators

Comparison operators are used to compare values. They include:

  • ==: Equal to
  • !=: Not equal to
  • >: Greater than
  • <: Less than
  • >=: Greater than or equal to
  • <=: Less than or equal to

Comparison operators in Python are used to compare two values and return a Boolean result (True or False). Here are some examples of comparison operators:

Equal to (==)

x = 100
y = 100
print(x == y) 

# Output
True

Not equal to (!=)

x = 100
y = 50
print(x != y) 

# Output
True

Greater than (>)

x = 100
y = 50
print(x > y) 

# Output
True

Less than (<)

x = 100
y = 50
print(x < y) 

# Output
False

Greater than or equal to (>=)

x = 100
y = 100
print(x >= y) 

# Output
True

Less than or equal to (<=)

x = 50
y = 50
print(x <= y) 

# Output
True

Chaining Comparison Operators

You can chain comparison operators in Python:

x = 5

# Check if x is greater than 2 and less than 10
print(2 < x < 10)

# Check if x is greater than or equal to 3 and less than or equal to 7
print(3 <= x <= 7)

# Chaining with strings
word = "hello"
print("a" < word < "z") # (lexicographically comparison)

# Chaining with lists
my_list = [1, 2, 3, 4, 5]
print(0 < my_list[0] < 10)  

# Chaining with variables
a = 5
b = 10
c = 15
print(a < b < c)  # True

# Output
True
True
True
True
True

Strings Comparison

str1 = "Apple"
str2 = "Pineapple"
print(str1 == str2)  
print(str1 != str2)  
print(str1 < str2)   # (lexicographically smaller)

# Output
False
True
True

Lists Comparison

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
list3 = [1, 2, 3, 4, 5]
print(list1 == list2)
print(list1 != list2)
print(list1 == list3)

# Output
False
True
True

Logical Operators

Logical operators are used to combine multiple conditions. They include:

  • and: Returns True if both conditions are true
  • or: Returns True if at least one condition is true
  • not: Returns True if the condition is false

Here are some examples:

AND Operator (and):

The and operator returns True if both conditions on its left and right are True, otherwise it returns False.

x = 100
y = 50

print(x > 90 and y < 100)
print(x >= 100 and y == 100)

# Output
True
False

OR Operator (or):

The or operator returns True if at least one of the conditions on its left or right is True, otherwise it returns False.

x = 100
y = 50

print(x > 90 or y < 100)
print(x >= 100 or y == 100)

# Output
True
True

NOT Operator (not):

The not operator negates the value of a condition. If the condition is True, not returns False. If the condition is False, not returns True.

x = 100
y = 50

print(not x == 100)
print(not y < 50)

# Output
False
True

Combining Operators:

Logical operators can be combined to form complex conditions:

x = 5
y = 10
z = 15

# Combination of AND and OR
print(x > 0 and y < 20 or z == 15)

# Combination of NOT and AND
print(not (x < 0 and y > 20))

# Output
True
True

Membership Operators

Membership operators in Python (in and not in) are used to test whether a value is a member of a sequence (e.g., strings, lists, tuples). Here are some examples:

in Operator:

# Checking if a character is in a string
print("a" in "apple")
print("z" in "apple")

# Checking if an element is in a list
my_list = [1, 2, 3, 4, 5, 6]
print(1 in my_list)
print(10 in my_list)

# Checking if a key is in a dictionary
my_dict = {"name": "Shivaay", "age": 6, "city": "Delhi"}
print("name" in my_dict)
print("salary" in my_dict)

# Output
True
False
True
False
True
False

not in Operator:

print("a" not in "apple")
print("z" not in "apple")

# Checking if an element is in a list
my_list = [1, 2, 3, 4, 5, 6]
print(1 not in my_list)
print(10 not in my_list)

# Checking if a key is in a dictionary
my_dict = {"name": "Shivaay", "age": 6, "city": "Delhi"}
print("name" not in my_dict)
print("salary" not in my_dict)

# Output
False
True
False
True
False
True

Identity Operators

Identity operators in Python (is and is not) are used to compare the memory locations of two objects. Here are some examples:

is Operator

x = [1, 2, 3]
y = [1, 2, 3]

# x and y are two different objects with the same values
print(x is y)  # False

# Assigning y to x, making both variables refer to the same object
x = y

# Now x and y refer to the same object
print(x is y)  # True

# Output
False
True

is not Operator

x = [1, 2, 3]
y = [1, 2, 3]

# x and y are two different objects with the same values
print(x is not y)  # True

# Assigning y to x, making both variables refer to the same object
x = y

# Now x and y refer to the same object
print(x is not y)  # False

# Output
True
False

In the first example, x and y are initially two separate objects with the same values, so x is y returns False. After assigning y to x, they both refer to the same object, so x is y returns True.

In the second example, x is not y returns True initially because x and y are different objects. After assigning y to x, they refer to the same object, so x is not y returns False.

These operators are useful when you need to check whether two variables refer to the same object in memory.