Week 3-2: Conditional Statements

CMPSC 100 Computational Expression

Janyl Jumadinova

Comparison Operations

Comparing values

Comparison Operators

These operators return boolean values (True/False):

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

Comparison Examples

x = 10
y = 5

print(x == y)   # False
print(x != y)   # True
print(x > y)    # True
print(x < y)    # False
print(x >= 10)  # True
print(y <= 5)   # True
num1 = 10
num2 = 5

print(num1 == num2)   # False
print(num1 != num2)   # True
print(num1 > num2)    # True
print(num1 < num2)    # False
print(num1 >= 10)     # True
print(num2 <= 5)      # True

String Comparisons

name1 = "Alice"
name2 = "Bob"
name3 = "Alice"

print(name1 == name3)  # True
print(name1 != name2)  # True
print(name1 < name2)   # True (alphabetical order)

Logical Operations

Combining boolean values

Logical Operators

Used to combine or modify boolean values:

  • and - Both conditions must be True
  • or - At least one condition must be True
  • not - Reverses the boolean value

Logical Examples

age = 20
has_license = True
is_student = False

# and operator
can_drive = age >= 16 and has_license
print(can_drive)  # True

# or operator
gets_discount = age < 18 or is_student
print(gets_discount)  # False

# not operator
is_adult = not age < 18
print(is_adult)  # True

Introduction to Conditional Statements

Making decisions in your code

What are Conditional Statements?

Conditional statements allow programs to make decisions:

  • Execute different code based on conditions
  • Branch your program’s flow
  • Respond to different inputs or situations
  • Essential for creating interactive programs

Real-world analogy: - “If it is raining, take an umbrella” - “If you’re hungry, eat something” - “If the temperature is below 32°F, water freezes”

Why Do We Need Conditionals?

Without conditionals, programs can only follow one path:

With conditionals, we can create responsive programs:

# With conditionals - responds to input
age = int(input("How old are you? "))
if age >= 18:
    print("You can vote!")
else:
    print("You can't vote yet.")

The if Statement

Basic decision making

Basic if Statement Syntax

The simplest conditional statement:

if condition:
    # code to execute if condition is True
    print("This runs when condition is True")

Key parts:

  • if keyword starts the statement
  • condition is evaluated as True or False
  • colon (:) ends the condition line
  • indentation shows which code belongs to the if block

if Statement Examples

Simple examples:

temperature = 75

if temperature > 70:
    print("It's warm outside!")

print("This always runs")

More examples:

score = 85
if score >= 90:
    print("You got an A!")

name = "Alice"
if name == "Alice":
    print("Hello, Alice!")

is_raining = True
if is_raining:
    print("Don't forget your umbrella!")

Conditions Use Comparison Operators

Review of comparison operators:

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

Examples:

age = 20
if age >= 18:    # True, so code executes
    print("You're an adult")

score = 75  
if score == 100:  # False, so code doesn't execute
    print("Perfect score!")

The else Statement

Handling the alternative

Adding else for Two Choices

Handle both True and False cases:

if condition:
    # code when condition is True
else:
    # code when condition is False

Example:

age = int(input("Enter your age: "))

if age >= 18:
    print("You can vote!")
else:
    print("You're too young to vote.")
    
print("Thank you!")  # This always runs

The elif Statement

Multiple conditions

Handling Multiple Conditions

When you need more than two choices:

if condition1:
    # code for condition1
elif condition2:
    # code for condition2
elif condition3:
    # code for condition3
else:
    # code when none of the above are true

Key points: - elif is short for “else if” - You can have multiple elif statements - Only the first True condition executes - else is optional and runs if nothing else is True

elif Examples

Grade calculator:

score = int(input("Enter your score: "))

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B") 
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

Logical Operators in Conditionals

Combining conditions

Using and, or, not

Combine multiple conditions:

  • and - Both conditions must be True
  • or - At least one condition must be True
  • not - Reverses True/False

Complex Logical Example

Age and grade level:

age = int(input("Enter age: "))
grade = int(input("Enter grade level: "))

if age >= 16 and grade >= 10:
    print("Eligible for work-study program")
elif age >= 14 or grade >= 9:
    print("Eligible for volunteer program")
else:
    print("Check back next year")

Nested Conditionals

Conditionals inside conditionals

What are Nested Conditionals?

Conditional statements inside other conditional statements:

if outer_condition:
    if inner_condition:
        print("Both conditions are true")
    else:
        print("Outer true, inner false")
else:
    print("Outer condition is false")

When to use: - When you need to check a second condition only after the first is true - For more complex decision-making logic - To avoid overly complicated logical operators

Nested Conditional Examples

Grade and extra credit:

score = int(input("Enter your test score: "))

if score >= 60:
    print("You passed!")
    
    if score >= 90:
        print("Excellent work!")
        if score == 100:
            print("Perfect score!")
    elif score >= 80:
        print("Good job!")
else:
    print("You need to retake the test.")

More Nested Examples

Weather and activity suggestions:

is_sunny = input("Is it sunny? (y/n): ") == "y"
temperature = float(input("What's the temperature? "))

if is_sunny:
    print("Great! It's sunny.")
    
    if temperature >= 75:
        print("Perfect for swimming!")
    elif temperature >= 60:
        print("Good for a picnic!")
    else:
        print("Sunny but chilly - wear a jacket!")
else:
    print("It's not sunny today.")
    
    if temperature >= 70:
        print("Still nice for indoor activities!")
    else:
        print("Good day to stay inside!")

Common Mistakes and Best Practices

Avoiding pitfalls

Common Mistakes

Indentation errors:

# Wrong - no indentation
if age >= 18:
print("You can vote!")  # IndentationError!

# Right - proper indentation
if age >= 18:
    print("You can vote!")

Using assignment instead of comparison:

# Wrong - assignment
if age = 18:  # SyntaxError!

# Right - comparison
if age == 18:

More Common Mistakes

Forgetting the colon:

# Wrong - missing colon
if age >= 18
    print("You can vote!")  # SyntaxError!

# Right - with colon
if age >= 18:
    print("You can vote!")

Comparing strings incorrectly:

# Case-sensitive comparison
name = input("Enter your name: ")  # User types "ALICE"
if name == "alice":  # This will be False!
    print("Hello, Alice!")

# Better approach
if name.lower() == "alice":
    print("Hello, Alice!")

Best Practices

Write clear conditions:

# Good - clear and readable
if student_age >= 18 and has_valid_id:
    print("Can enter the venue")

# Avoid overly complex conditions
if age >= 18 and (has_id == True) and not (is_banned == True):
    # Too complicated!

Use meaningful variable names:

# Good
if temperature > freezing_point:
    print("Water is liquid")

# Less clear
if t > 32:
    print("Water is liquid")