Python
Conditional Statements

A Comprehensive Guide to Conditional Statements in Python

Conditional statements allow us to control the flow of our program based on certain conditions. They help us make decisions and execute specific blocks of code based on the evaluation of conditions. In this post, we will explore the different types of conditional statements in Python, including if statements, if-else statements, if-elif-else statements, and nested conditionals. We will also cover conditional tests and provide code examples for each section.

Conditional Tests

Conditional tests evaluate a condition to determine if it is true or false. These tests are the building blocks of conditional statements. In Python, we have various conditional operators to compare values, including:

  • Equality operator (==): Checks if two values are equal.
  • Inequality operator (!=): Checks if two values are not equal.
  • Greater than operator (>): Checks if the left operand is greater than the right operand.
  • Less than operator (<): Checks if the left operand is less than the right operand.
  • Greater than or equal to operator (>=): Checks if the left operand is greater than or equal to the right operand.
  • Less than or equal to operator (<=): Checks if the left operand is less than or equal to the right operand.

Here's an example of using conditional tests:

x = 5
y = 10
 
# Equality test
if x == y:
    print("x is equal to y") 
 
# Inequality test
if x != y:
    print("x is not equal to y") # Output: x is not equal to y
 
# Greater than test
if x > y:
    print("x is greater than y")
 
# Less than test
if x < y:
    print("x is less than y") # Output: x is less than y
 
# Greater than or equal to test
if x >= y:
    print("x is greater than or equal to y")
 
# Less than or equal to test
if x <= y:
    print("x is less than or equal to y") 
# Output: x is less than or equal to y

In this example, we perform various conditional tests comparing the values of x and y. The appropriate print statements are executed based on the evaluation of each condition.

if Statements

The if statement allows us to execute a block of code only if a certain condition is true. If the condition is false, the block of code is skipped. The general syntax of an if statement is as follows:

if condition:
    # code block

Here's an example:

age = 25
 
if age >= 18:
    print("You are eligible to vote.")
    
# Output: You are eligible to vote.

In this example, the code inside the if statement is executed only if the age variable is greater than or equal to 18.

if-else Statements

The if-else statement allows us to execute one block of code if a condition is true, and a different block of code if the condition is false. The general syntax of an if-else statement is as follows:

if condition:
    # code block executed if condition is true
else:
    # code block executed if condition is false

Here's an example:

age = 15
 
if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")
    
# Output: You are not eligible to vote.

In this example, if the age variable is greater than or equal to 18, the first block of code is executed. Otherwise, the second block of code is executed.

if-elif-else Statements

The if-elif-else statement allows us to handle multiple conditions and execute different blocks of code based on the evaluation of those conditions. The general syntax of an if-elif-else statement is as follows:

if condition1:
    # code block executed if condition1 is true
elif condition2:
    # code block executed if condition2 is true
else:
    # code block executed if all conditions are false

Here's an example:

score = 75
 
if score >= 90:
    print("You got an A.")
elif score >= 80:
    print("You got a B.")
elif score >= 70:
    print("You got a C.")
else:
    print("You need to improve your score.")
 
# Output: You got a C.

In this example, different blocks of code are executed based on the value of the score variable. The conditions are evaluated sequentially, and only the block corresponding to the first true condition is executed.

Nested Conditionals

Nested conditionals are conditional statements that are placed inside another conditional statement. They allow for more complex decision-making based on multiple conditions. Here's an example:

x = 10
y = 5
 
if x > y:
    if x % y == 0:
        print("x is divisible by y.")
    else:
        print("x is not divisible by y.")
else:   
 print("x is not greater than y.")
 
# Output" x is divisible by y.

In this example, the inner if statement is nested inside the outer if statement. The code inside the inner if statement is executed only if the condition x > y is true.

Multiple Conditional Tests with and and or Operator

In addition to single conditional tests, Python provides the and and or operators to combine multiple conditions in conditional statements. These operators allow you to check for multiple conditions simultaneously. Let's explore how to use and and or in conditional statements.

Using and Operator

The and operator evaluates to True if both the left and right conditions are True. If either condition is False, the overall expression evaluates to False. Here's an example:

age = 25
citizenship = "USA"
 
if age >= 18 and citizenship == "USA":
    print("You are eligible to vote in the USA.")
 
#Output: You are eligible to vote in the USA.

In this example, the and operator is used to combine two conditions: age >= 18 and citizenship == "USA". Both conditions must be True for the if statement's code block to be executed.

Using or Operator

The or operator evaluates to True if at least one of the left or right conditions is True. It only evaluates the second condition if the first condition is False. Here's an example:

temperature = 25
weather = "sunny"
 
if temperature > 30 or weather == "sunny":
    print("It's a hot day.")
 
# Output: It's a hot day.

In this example, the or operator is used to combine two conditions: temperature > 30 and weather == "sunny". If either condition is True, the code block inside the if statement will be executed.

Combining and and or Operators

You can combine and and or operators to create more complex conditions in your conditional statements. Here's an example:

age = 16
country = "Canada"
 
if (age >= 18 and country == "USA") or (age >= 19 and country == "Canada"):
    print("You are eligible to vote.")

In this example, the condition checks if the age is greater than or equal to 18 and the country is "USA", or if the age is greater than or equal to 19 and the country is "Canada". If any of these conditions is True, the code block will be executed.

Truthiness and Falsiness

It's important to note that not all conditions in Python need to be explicitly True or False. Certain values are considered "truthy" or "falsy". In conditional statements, these truthy and falsy values are evaluated accordingly. For example:

name = ""
 
if name:
    print("Name is not empty.")
else:
    print("Name is empty.")
 
#Output: Name is empty.

In this example, an empty string "" is considered "falsy". Therefore, the code block inside the else statement will be executed, indicating that the name is empty.

Using in and not in Conditions in if Statements

In addition to the comparison operators, Python provides the in and not in operators to check if a value exists in a sequence or not. These operators are particularly useful when you want to check membership or absence in a collection of values. Let's explore how to use in and not in conditions in if statements.

Using in Operator

The in operator checks if a value exists in a sequence. It returns True if the value is found, and False otherwise. Here's an example:

fruits = ['apple', 'banana', 'orange']
 
if 'apple' in fruits:
    print("Apple is in the list of fruits.")
# Output: Apple is in the list of fruits.

In this example, the in operator is used to check if the value 'apple' exists in the fruits list. If the condition is True, the code block inside the if statement will be executed.

Using not in Operator

The not in operator checks if a value does not exist in a sequence. It returns True if the value is not found, and False otherwise. Here's an example:

fruits = ['apple', 'banana', 'orange']
 
if 'grape' not in fruits:
    print("Grape is not in the list of fruits.")
# Output: Grape is not in the list of fruits.

In this example, the not in operator is used to check if the value 'grape' does not exist in the fruits list. If the condition is True, the code block inside the if statement will be executed.

Using in and not in with Strings

The in and not in operators are not limited to lists. They can also be used with other sequences, such as strings. Here's an example:

text = "Hello, World!"
 
if 'Hello' in text:
    print("The text contains 'Hello'.")
# Output: The text contains 'Hello'.

In this example, the in operator is used to check if the substring 'Hello' exists in the text string. If the condition is True, the code block inside the if statement will be executed.

Combining with Other Conditions

You can combine in or not in conditions with other conditions using logical operators such as and and or. This allows you to create more complex conditions in your if statements. Here's an example:

fruits = ['apple', 'banana', 'orange']
count = 3
 
if 'apple' in fruits and count > 0:
    print("There is at least one apple available.")
# Output: There is at least one apple available.

In this example, the condition checks if 'apple' exists in the fruits list and if the count variable is greater than 0. Only if both conditions are True, the code block inside the if statement will be executed.