What are Conditionals?

Conditional statements allow your program to make decisions based on conditions. They execute different code blocks depending on whether conditions are True or False.

if Statement

The basic conditional statement:

age = 18

if age >= 18:
    print("You are an adult")
    print("You can vote")

if-else Statement

Execute code when condition is False:

age = 16

if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")

if-elif-else Statement

Check multiple conditions:

score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Your grade is {grade}")

Nested Conditionals

Conditionals inside conditionals:

age = 20
has_license = True

if age >= 18:
    if has_license:
        print("You can drive")
    else:
        print("You need a license")
else:
    print("You are too young to drive")

Ternary Operator

Short form for simple conditionals:

age = 20
status = "adult" if age >= 18 else "minor"
print(status)  # "adult"

# Equivalent to:
if age >= 18:
    status = "adult"
else:
    status = "minor"

Multiple Conditions

Combine conditions with logical operators:

age = 25
has_license = True
has_insurance = True

if age >= 18 and has_license and has_insurance:
    print("You can drive legally")

if age < 18 or not has_license:
    print("You cannot drive")

Common Patterns

Checking if value exists

name = ""

if name:
    print(f"Hello, {name}")
else:
    print("No name provided")

Checking list membership

fruits = ["apple", "banana", "orange"]

if "apple" in fruits:
    print("Apple is available")

Best Practices

  • Keep conditions simple: Avoid complex nested conditionals
  • Use elif: Prefer elif over multiple if statements when checking the same variable
  • Early returns: Handle edge cases first
  • Readable conditions: Use descriptive variable names

Next Steps

Combine conditionals with loops for powerful program control.