Conditional Statements in Python

Conditional Statements in Python

What Are Conditional Statements?

  • Control the flow of your program based on conditions.
  • The most common statement is the if statement, which executes code only when a condition is true.
  • Useful for decision-making in various applications, including NLP tasks.

Importance in NLP

  • Adjust processing based on conditions (e.g., text case, keyword presence).
  • Enable flexible and dynamic responses to input data.
word = "HELLO"
if word.isupper():
    print("The word is uppercase!")  # Output: The word is uppercase!
The word is uppercase!

The if Statement

Basic Syntax of if

  • Check a condition and execute a block of code if it evaluates to True.
x = 10
if x > 5:
    print("x is greater than 5")  # Output: x is greater than 5
x is greater than 5

Explanation

  • The condition x > 5 is checked.
  • Since x is 10, the print statement executes.

The else Statement

Using the else Statement

  • Defines what happens when the if condition is False.
x = 3
if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")  # Output: x is not greater than 5
x is not greater than 5

Explanation

  • Since x is 3, the else block executes, printing “x is not greater than 5”.

The elif Statement

Multiple Conditions with elif

  • Use elif to check additional conditions if the previous ones are false.
x = 7
if x > 10:
    print("x is greater than 10")
elif x > 5:
    print("x is greater than 5 but less than or equal to 10")  # Output: x is greater than 5 but less than or equal to 10
else:
    print("x is less than or equal to 5")
x is greater than 5 but less than or equal to 10

Explanation

  • Python checks each condition sequentially; x > 10 is false, but x > 5 is true.

Using Comparison Operators

Common Comparison Operators

  • ==: Equal to
  • !=: Not equal to
  • >: Greater than
  • <: Less than
  • >=: Greater than or equal to
  • <=: Less than or equal to
age = 18
if age == 18:
    print("You are 18 years old")  # Output: You are 18 years old
if age != 20:
    print("You are not 20 years old")  # Output: You are not 20 years old
You are 18 years old
You are not 20 years old

Explanation

  • The == operator checks if age is 18, while the != operator checks if it is not 20.

Logical Operators

Combining Conditions

  • Use logical operators to evaluate multiple conditions.
x = 7

if x > 5 and x < 10:
    print("x is between 5 and 10")  # Output: x is between 5 and 10
x is between 5 and 10

Other Logical Operators

  • or: True if at least one condition is true.
  • not: Inverts the truth value of the condition.
if x < 5 or x > 6:
    print("x is either less than 5 or greater than 6")  # Output: x is either less than 5 or greater than 6

if not x == 5:
    print("x is not equal to 5")  # Output: x is not equal to 5
x is either less than 5 or greater than 6
x is not equal to 5

Nested if Statements

What Are Nested if Statements?

  • Place one if statement inside another to check multiple conditions that depend on each other.
x = 10
y = 20

if x > 5:
    if y > 15:
        print("x is greater than 5 and y is greater than 15")  # Output: x is greater than 5 and y is greater than 15
x is greater than 5 and y is greater than 15

Explanation

  • First check x > 5. If true, then check y > 15.

Checking Membership with in Operator

Using the in Operator

  • Check if a value exists in a collection (e.g., list, string, tuple).
fruits = ["apple", "banana", "cherry"]

if "banana" in fruits:
    print("Banana is in the list!")  # Output: Banana is in the list!
Banana is in the list!

Example with Strings

sentence = "Hello world"
if "world" in sentence:
    print("The word 'world' is in the sentence.")  # Output: The word 'world' is in the sentence.
The word 'world' is in the sentence.

Combining Conditions in Practical Examples

Example: Password Validation

  • Check user input against certain conditions for validity.
password = "Hello123"

if len(password) >= 8 and any(char.isdigit() for char in password):
    print("Password is valid")  # Output: Password is valid
else:
    print("Password must be at least 8 characters long and contain a number.")
Password is valid

Explanation

  • Checks for length and if any character is a digit using char.isdigit().

Edge Cases and Handling Errors

Importance of Edge Case Handling

  • Think about situations where input values might cause errors, such as empty strings or division by zero.
# Checking for division by zero
numerator = 10
denominator = 0

if denominator != 0:
    result = numerator / denominator
    print(result)
else:
    print("Cannot divide by zero")  # Output: Cannot divide by zero
Cannot divide by zero

Explanation

  • Use conditionals to prevent errors like division by zero by checking if the denominator is not zero.