Skip to content

If-Else Statements

Conditional statements allow your program to make decisions.

Basic If Statement

let age = 18;

if age >= 18 {
    print "You are an adult";
}

If-Else Statement

let age = 15;

if age >= 18 {
    print "You are an adult";
} else {
    print "You are a minor";
}

If-Else If-Else

let score = 85;

if score >= 90 {
    print "Grade: A";
} else {
    if score >= 80 {
        print "Grade: B";
    } else {
        if score >= 70 {
            print "Grade: C";
        } else {
            print "Grade: F";
        }
    }
}

Conditions

Comparison Conditions

let x = 10;

if x > 5 {
    print "x is greater than 5";
}

if x == 10 {
    print "x equals 10";
}

if x != 0 {
    print "x is not zero";
}

Logical Conditions

let age = 25;
let has_license = true;

// AND condition
if age >= 18 && has_license == true {
    print "Can drive";
}

// OR condition
if age < 18 || has_license == false {
    print "Cannot drive";
}

// NOT condition
if !has_license {
    print "No license";
}

Complex Conditions

let score = 85;
let attendance = 90;

if (score >= 80 && attendance >= 85) || score >= 95 {
    print "Pass with honors";
}

Truthy and Falsy Values

// Non-zero numbers are truthy
if 1 {
    print "This prints";
}

// Zero is falsy
if 0 {
    print "This doesn't print";
}

// Non-empty strings are truthy
if "hello" {
    print "This prints";
}

// Empty strings are falsy
if "" {
    print "This doesn't print";
}

Nested If Statements

let age = 20;
let student = true;

if age >= 18 {
    if student == true {
        print "Adult student discount applies";
    } else {
        print "Regular adult price";
    }
} else {
    print "Youth price";
}

Common Patterns

Range Checking

let temperature = 75;

if temperature < 32 {
    print "Freezing";
} else {
    if temperature >= 32 && temperature < 60 {
        print "Cold";
    } else {
        if temperature >= 60 && temperature < 80 {
            print "Mild";
        } else {
            print "Hot";
        }
    }
}

Validation

let username = input("Enter username: ");

if len(username) < 3 {
    print "Username too short";
} else {
    if len(username) > 20 {
        print "Username too long";
    } else {
        print "Username accepted";
    }
}