ProtoLang.net

Reference: Else

☰ Hide Sidebar
TOKEN ELSE
ALIAS None

The Else token is used within If statements to provide a default code block that executes when all previous If and Elif conditions evaluate to False. The Else clause does not have its own condition - it automatically executes when no other conditions in the statement have been met. An Else clause is optional and can only appear once at the end of an If statement.

Syntax

The short syntax structure uses the word ELSE:

IF CONDITION
    STATEMENTS
ELSE
    STATEMENTS
END IF

The long syntax structure uses the word ELSE:

IF CONDITION
    STATEMENTS
ELSE
    STATEMENTS
END IF

Basic Else Usage

Else provides a fallback when the If condition is False.

Example: Simple If-Else

NEW INT age = 16
IF age >= 18
    PRINTLN "You can vote"
ELSE
    PRINTLN "You cannot vote yet"
END IF
// Displays "You cannot vote yet"

Example: Else with Boolean

NEW BOOL isLoggedIn = FALSE
IF isLoggedIn == TRUE
    PRINTLN "Welcome back"
ELSE
    PRINTLN "Please log in"
END IF
// Displays "Please log in"

Example: Else with String Comparison

NEW STR password = "wrong123"
IF password == "correct123"
    PRINTLN "Access granted"
ELSE
    PRINTLN "Access denied"
END IF
// Displays "Access denied"

Example: Else with Float Comparison

NEW FLOAT balance = 25.50
IF balance >= 100.0
    PRINTLN "High balance"
ELSE
    PRINTLN "Low balance"
END IF
// Displays "Low balance"

Default Else Case

Else a acts catch-all for any values not handled by previous conditions.

Example: Default Handler

NEW STR status = "unknown"
IF status == "active"
    PRINTLN "System is active"
ELSE
    PRINTLN "System is not active"
END IF
// Displays "System is not active"

Example: Out of Range Default

NEW INT value = 150
IF ( value >= 0 ) && ( value <= 100 )
    PRINTLN "Value is in range"
ELSE
    PRINTLN "Value is out of range"
END IF
// Displays "Value is out of range"

Example: Invalid Input Handler

NEW INT choice = 99
IF ( choice >= 1 ) && ( choice <= 5 )
    PRINTLN "Valid menu choice"
ELSE
    PRINTLN "Invalid choice - please select 1-5"
END IF
// Displays "Invalid choice - please select 1-5"

Example: Error Fallback

NEW INT errorCode = 0
IF errorCode == 0
    PRINTLN "Success"
ELSE
    PRINTLN "Error occurred: " .. errorCode
END IF
// Displays "Success"

Else with Elif

Else provides a default case after all If and Elif conditions have been checked.

Example: If-Elif-Else Chain

NEW INT score = 55
IF score >= 90
    PRINTLN "Grade: A"
ELIF score >= 80
    PRINTLN "Grade: B"
ELIF score >= 70
    PRINTLN "Grade: C"
ELIF score >= 60
    PRINTLN "Grade: D"
ELSE
    PRINTLN "Grade: F"
END IF
// Displays "Grade: F"

Example: Multiple Elif with Else

NEW INT day = 9
IF day == 1
    PRINTLN "Monday"
ELIF day == 2
    PRINTLN "Tuesday"
ELIF day == 3
    PRINTLN "Wednesday"
ELIF day == 4
    PRINTLN "Thursday"
ELIF day == 5
    PRINTLN "Friday"
ELIF day == 6
    PRINTLN "Saturday"
ELIF day == 7
    PRINTLN "Sunday"
ELSE
    PRINTLN "Invalid day number"
END IF
// Displays "Invalid day number"

Example: Status with Default

NEW STR orderStatus = "cancelled"
IF orderStatus == "pending"
    PRINTLN "Order is being processed"
ELIF orderStatus == "shipped"
    PRINTLN "Order is on the way"
ELIF orderStatus == "delivered"
    PRINTLN "Order has been delivered"
ELSE
    PRINTLN "Order status: " .. orderStatus
END IF
// Displays "Order status: cancelled"

Example: Temperature Categories with Else

NEW FLOAT temp = 5.0
IF temp >= 90.0
    PRINTLN "Very hot"
ELIF temp >= 75.0
    PRINTLN "Warm"
ELIF temp >= 60.0
    PRINTLN "Mild"
ELIF temp >= 40.0
    PRINTLN "Cool"
ELIF temp >= 20.0
    PRINTLN "Cold"
ELSE
    PRINTLN "Very cold"
END IF
// Displays "Very cold"

Execution Guarantee

When an Else clause is present, exactly one code block in the If-Elif-Else chain will always execute.

Example: Guaranteed Execution

NEW INT x = 50
IF x < 50
    PRINTLN "Less than 50"
ELSE
    PRINTLN "50 or greater"
END IF
// Displays "50 or greater"

Example: Either-Or Scenario

NEW BOOL isWeekend = FALSE
IF isWeekend == TRUE
    PRINTLN "Enjoy your weekend!"
ELSE
    PRINTLN "Have a productive work day!"
END IF
// Displays "Have a productive work day!"

Example: One Block Always Runs

NEW INT number = 7
IF ( number % 2 ) == 0
    PRINTLN number .. " is even"
ELSE
    PRINTLN number .. " is odd"
END IF
// Displays "7 is odd"

Modifying Variables in Else Block

Variables can be created or modified within Else blocks using New and Set commands.

Example: Setting Default Value

NEW INT score = 45
NEW STR grade = ""
IF score >= 90
    SET grade = "A"
ELIF score >= 80
    SET grade = "B"
ELIF score >= 70
    SET grade = "C"
ELIF score >= 60
    SET grade = "D"
ELSE
    SET grade = "F"
END IF
PRINTLN "Final grade: " .. grade
// Displays "Final grade: F"

Example: Default Discount

NEW BOOL isMember = FALSE
NEW FLOAT discountRate = 0.0
IF isMember == TRUE
    SET discountRate = 0.15
ELSE
    SET discountRate = 0.0
END IF
PRINTLN "Discount: " .. ( discountRate * 100.0 ) .. "%"
// Displays "Discount: 0.0%"

Example: Multiple Variable Updates in Else

NEW FLOAT balance = 50.0
NEW FLOAT fee = 0.0
NEW STR status = ""
IF balance >= 1000.0
    SET fee = 0.0
    SET status = "Premium"
ELIF balance >= 500.0
    SET fee = 5.0
    SET status = "Standard"
ELSE
    SET fee = 10.0
    SET status = "Basic"
END IF
PRINTLN "Account status: " .. status
PRINTLN "Monthly fee: $" .. fee
// Displays "Account status: Basic" and "Monthly fee: $10.0"

Example: Counter in Else

NEW INT attempts = 5
NEW INT maxAttempts = 3
NEW INT remainingAttempts = 0
IF attempts <= maxAttempts
    SET remainingAttempts = maxAttempts - attempts
    PRINTLN "Attempts remaining: " .. remainingAttempts
ELSE
    SET remainingAttempts = 0
    PRINTLN "Maximum attempts exceeded"
END IF
// Displays "Maximum attempts exceeded"

Nested Else Statements

Else blocks can contain nested If-Elif-Else statements.

Example: Nested If-Else

NEW INT age = 16
NEW BOOL hasPermission = TRUE
IF age >= 18
    PRINTLN "Adult - full access"
ELSE
    IF hasPermission == TRUE
        PRINTLN "Minor with parental permission"
    ELSE
        PRINTLN "Minor without permission - restricted"
    END IF
END IF
// Displays "Minor with parental permission"

Example: Multi-Level Nesting

NEW INT priority = 3
NEW BOOL urgent = FALSE
IF priority == 1
    PRINTLN "Critical priority"
ELSE
    IF priority == 2
        PRINTLN "High priority"
    ELSE
        IF urgent == TRUE
            PRINTLN "Medium priority - marked urgent"
        ELSE
            PRINTLN "Standard priority"
        END IF
    END IF
END IF
// Displays "Standard priority"

Example: Nested Default Cases

NEW STR userType = "guest"
NEW BOOL hasAccess = FALSE
IF userType == "admin"
    PRINTLN "Admin access granted"
ELSE
    IF userType == "user"
        PRINTLN "User access granted"
    ELSE
        IF hasAccess == TRUE
            PRINTLN "Guest with special access"
        ELSE
            PRINTLN "Limited guest access"
        END IF
    END IF
END IF
// Displays "Limited guest access"

Example: Nested Validation

NEW STR username = "user123"
NEW STR password = "wrong"
IF username == "admin"
    IF password == "admin123"
        PRINTLN "Admin login successful"
    ELSE
        PRINTLN "Admin password incorrect"
    END IF
ELSE
    IF password == "user123"
        PRINTLN "User login successful"
    ELSE
        PRINTLN "User password incorrect"
    END IF
END IF
// Displays "User password incorrect"

Practical Applications

Example: Input Validation

NEW INT quantity = -5
IF ( quantity >= 1 ) && ( quantity <= 100 )
    PRINTLN "Valid quantity: " .. quantity
ELSE
    PRINTLN "Invalid quantity - must be between 1 and 100"
END IF
// Displays "Invalid quantity - must be between 1 and 100"

Example: Access Control

NEW INT age = 21
NEW BOOL hasID = TRUE
IF ( age >= 21 ) && hasID
    PRINTLN "Entry permitted"
ELSE
    PRINTLN "Entry denied"
END IF
// Displays "Entry permitted"

Example: Discount Eligibility

NEW FLOAT purchaseAmount = 45.0
NEW FLOAT minPurchase = 50.0
NEW FLOAT discount = 0.0
IF purchaseAmount >= minPurchase
    SET discount = purchaseAmount * 0.10
    PRINTLN "Discount applied: $" .. discount
ELSE
    PRINTLN "Spend $" .. ( minPurchase - purchaseAmount ) .. " more for 10% discount"
END IF
// Displays "Spend $5.0 more for 10% discount"

Example: Stock Availability

NEW INT stock = 0
IF stock > 0
    PRINTLN "In stock: " .. stock .. " available"
ELSE
    PRINTLN "Out of stock - please check back later"
END IF
// Displays "Out of stock - please check back later"

Example: Temperature Warning System

NEW FLOAT engineTemp = 110.0
NEW FLOAT maxTemp = 100.0
IF engineTemp <= maxTemp
    PRINTLN "Temperature normal: " .. engineTemp
ELSE
    PRINTLN "WARNING: Temperature exceeds safe limit!"
    PRINTLN "Current: " .. engineTemp .. " / Max: " .. maxTemp
END IF
// Displays warning messages

Example: Password Strength Checker

NEW INT passwordLength = 6
NEW INT minLength = 8
IF passwordLength >= minLength
    PRINTLN "Password meets minimum requirements"
ELSE
    NEW INT needed = minLength - passwordLength
    PRINTLN "Password too short - need " .. needed .. " more characters"
END IF
// Displays "Password too short - need 2 more characters"

Example: Age-Based Pricing

NEW INT age = 70
NEW FLOAT ticketPrice = 0.0
IF age < 5
    SET ticketPrice = 0.0
    PRINTLN "Free admission for children under 5"
ELIF age < 18
    SET ticketPrice = 12.0
    PRINTLN "Youth ticket: $" .. ticketPrice
ELIF age < 65
    SET ticketPrice = 20.0
    PRINTLN "Adult ticket: $" .. ticketPrice
ELSE
    SET ticketPrice = 15.0
    PRINTLN "Senior ticket: $" .. ticketPrice
END IF
// Displays "Senior ticket: $15.0"

Example: Overtime Calculator

NEW INT hoursWorked = 45
NEW INT regularHours = 40
NEW INT overtimeHours = 0
IF hoursWorked <= regularHours
    PRINTLN "Regular hours: " .. hoursWorked
ELSE
    SET overtimeHours = hoursWorked - regularHours
    PRINTLN "Regular hours: " .. regularHours
    PRINTLN "Overtime hours: " .. overtimeHours
END IF
// Displays regular and overtime hours

Example: Division by Zero Protection

NEW INT numerator = 100
NEW INT denominator = 0
IF denominator != 0
    NEW INT result = numerator / denominator
    PRINTLN "Result: " .. result
ELSE
    PRINTLN "Error: Cannot divide by zero"
END IF
// Displays "Error: Cannot divide by zero"

Example: Credit Score Category

NEW INT creditScore = 580
NEW STR category = ""
IF creditScore >= 800
    SET category = "Excellent"
ELIF creditScore >= 740
    SET category = "Very Good"
ELIF creditScore >= 670
    SET category = "Good"
ELIF creditScore >= 580
    SET category = "Fair"
ELSE
    SET category = "Poor"
END IF
PRINTLN "Credit rating: " .. category
// Displays "Credit rating: Fair"

Else in Loops

Example: Else Inside While Loop

NEW INT i = 1
WHILE i <= 5
    IF ( i % 2 ) == 0
        PRINTLN i .. " is even"
    ELSE
        PRINTLN i .. " is odd"
    END IF
    SET i = i + 1
END WHILE
// Displays odd/even classification for 1 through 5

Example: Conditional Accumulation

NEW INT i = 1
NEW INT evenSum = 0
NEW INT oddSum = 0
WHILE i <= 10
    IF ( i % 2 ) == 0
        SET evenSum = evenSum + i
    ELSE
        SET oddSum = oddSum + i
    END IF
    SET i = i + 1
END WHILE
PRINTLN "Even sum: " .. evenSum
PRINTLN "Odd sum: " .. oddSum
// Displays "Even sum: 30" and "Odd sum: 25"

Example: Filtering in Loop

NEW INT num = 1
NEW INT passCount = 0
NEW INT failCount = 0
WHILE num <= 10
    IF num >= 5
        SET passCount = passCount + 1
    ELSE
        SET failCount = failCount + 1
    END IF
    SET num = num + 1
END WHILE
PRINTLN "Pass: " .. passCount
PRINTLN "Fail: " .. failCount
// Displays "Pass: 6" and "Fail: 4"

Example: Range-Based Processing

NEW INT value = 10
WHILE value <= 50
    IF value < 30
        PRINTLN value .. " - Low range"
    ELSE
        PRINTLN value .. " - High range"
    END IF
    SET value = value + 10
END WHILE

Else with All Data Types

Example: Boolean Default

NEW BOOL isVerified = FALSE
IF isVerified == TRUE
    PRINTLN "Account verified"
ELSE
    PRINTLN "Please verify your account"
END IF
// Displays "Please verify your account"

Example: Integer Threshold

NEW INT level = 3
IF level >= 10
    PRINTLN "Expert level"
ELSE
    PRINTLN "Beginner or intermediate level"
END IF
// Displays "Beginner or intermediate level"

Example: Float Range Check

NEW FLOAT gpa = 2.8
IF gpa >= 3.5
    PRINTLN "Dean's List"
ELSE
    PRINTLN "Standard standing"
END IF
// Displays "Standard standing"

Example: String Matching

NEW STR command = "help"
IF command == "start"
    PRINTLN "Starting system..."
ELIF command == "stop"
    PRINTLN "Stopping system..."
ELSE
    PRINTLN "Unknown command: " .. command
END IF
// Displays "Unknown command: help"

Else Without Elif

Else can be used directly after If without any Elif clauses.

Example: Binary Choice

NEW STR answer = "no"
IF answer == "yes"
    PRINTLN "You agreed"
ELSE
    PRINTLN "You declined"
END IF
// Displays "You declined"

Example: Pass/Fail

NEW INT score = 58
IF score >= 60
    PRINTLN "Pass"
ELSE
    PRINTLN "Fail"
END IF
// Displays "Fail"

Example: True/False Response

NEW BOOL condition = FALSE
IF condition == TRUE
    PRINTLN "Condition met"
ELSE
    PRINTLN "Condition not met"
END IF
// Displays "Condition not met"

Example: Above/Below Check

NEW FLOAT temperature = 98.2
NEW FLOAT normal = 98.6
IF temperature >= normal
    PRINTLN "Normal or high temperature"
ELSE
    PRINTLN "Below normal temperature"
END IF
// Displays "Below normal temperature"

Complex Else Scenarios

Example: Multi-Factor Decision

NEW FLOAT income = 45000.0
NEW INT creditScore = 680
NEW FLOAT debt = 15000.0
IF ( income >= 50000.0 ) && ( creditScore >= 700 ) && ( debt < 10000.0 )
    PRINTLN "Loan approved - excellent terms"
ELIF ( income >= 40000.0 ) && ( creditScore >= 650 )
    PRINTLN "Loan approved - standard terms"
ELSE
    PRINTLN "Loan application requires review"
END IF
// Displays "Loan application requires review"

Example: Cascading Validation

NEW STR username = "user"
NEW STR password = "pass"
NEW INT twoFactorCode = 1234
IF username == "admin"
    IF password == "admin123"
        IF twoFactorCode == 9876
            PRINTLN "Full admin access"
        ELSE
            PRINTLN "Invalid two-factor code"
        END IF
    ELSE
        PRINTLN "Invalid admin password"
    END IF
ELSE
    PRINTLN "Not an admin account"
END IF
// Displays "Not an admin account"

Example: Comprehensive Error Handling

NEW INT fileSize = 15000
NEW INT maxSize = 10000
NEW INT minSize = 100
IF fileSize > maxSize
    PRINTLN "Error: File too large"
    PRINTLN "Maximum size: " .. maxSize .. " bytes"
ELIF fileSize < minSize
    PRINTLN "Error: File too small"
    PRINTLN "Minimum size: " .. minSize .. " bytes"
ELSE
    PRINTLN "File size acceptable: " .. fileSize .. " bytes"
END IF
// Displays error message about file being too large

Important Notes

  • Else can only appear once in an If statement.
  • Else must be the last clause before END IF.
  • Else does not have its own condition - it executes when all previous conditions are False.
  • Else is optional - If statements can exist without an Else clause.
  • When Else is present, exactly one code block in the If-Elif-Else chain will execute.
  • Else cannot appear before Elif clauses.
  • Variables modified in Else blocks affect the global scope ( unless inside a function ).
  • Else blocks can contain any valid ProtoLang statements including nested If statements.
  • Else provides a catch-all for values not explicitly handled by If/Elif conditions.
  • Use Else for default values, error handling, and validation fallbacks.

Common Errors

Error: Else Without If

NEW INT x = 5
ELSE // Syntax error! ELSE must follow IF
    PRINTLN "Something"
END IF
// Correct:
IF x > 10
    PRINTLN "Greater than 10"
ELSE
    PRINTLN "10 or less"
END IF

Error: Else Before Elif

NEW INT score = 75
IF score >= 90
    PRINTLN "A"
ELSE
    PRINTLN "Not an A"
ELIF score >= 80 // Syntax error! ELIF cannot come after ELSE
    PRINTLN "B"
END IF
// Correct:
IF score >= 90
    PRINTLN "A"
ELIF score >= 80
    PRINTLN "B"
ELSE
    PRINTLN "Not A or B"
END IF

Error: Multiple Else Clauses

NEW INT x = 5
IF x > 10
    PRINTLN "High"
ELSE
    PRINTLN "Not high"
ELSE // Syntax error! Only one ELSE allowed
    PRINTLN "This is wrong"
END IF
// Correct:
IF x > 10
    PRINTLN "High"
ELIF x > 5
    PRINTLN "Medium"
ELSE
    PRINTLN "Low"
END IF

Error: Else with Condition

NEW INT x = 5
IF x > 10
    PRINTLN "Greater than 10"
ELSE x > 5 // Syntax error! ELSE does not take a condition
    PRINTLN "Greater than 5"
END IF
// Correct: Use ELIF for additional conditions
IF x > 10
    PRINTLN "Greater than 10"
ELIF x > 5
    PRINTLN "Greater than 5"
ELSE
    PRINTLN "5 or less"
END IF

Error: Missing END IF

NEW INT x = 5
IF x > 10
    PRINTLN "Greater than 10"
ELSE
    PRINTLN "10 or less"
// Syntax error! Missing END IF
// Correct:
IF x > 10
    PRINTLN "Greater than 10"
ELSE
    PRINTLN "10 or less"
END IF

Error: Else After END IF

NEW INT x = 5
IF x > 10
    PRINTLN "Greater than 10"
END IF
ELSE // Syntax error! ELSE must come before END IF
    PRINTLN "10 or less"
END IF
// Correct:
IF x > 10
    PRINTLN "Greater than 10"
ELSE
    PRINTLN "10 or less"
END IF

Error: Standalone Else Block

ELSE // Syntax error! ELSE requires an IF
    PRINTLN "This won't work"
END IF
// Correct:
NEW BOOL ready = FALSE
IF ready == TRUE
    PRINTLN "Ready"
ELSE
    PRINTLN "Not ready"
END IF

Error: Else in Wrong Position

NEW INT score = 85
ELSE // Syntax error! ELSE must follow IF or ELIF
    PRINTLN "Default"
IF score >= 90
    PRINTLN "A"
END IF
// Correct:
IF score >= 90
    PRINTLN "A"
ELSE
    PRINTLN "Not an A"
END IF

Error: Empty Else Block Confusion

NEW INT x = 5
IF x > 10
    PRINTLN "Greater than 10"
ELSE
    // Empty block is valid but does nothing
END IF
// This is valid but Else block has no effect
// Better: Remove Else if not needed
IF x > 10
    PRINTLN "Greater than 10"
END IF

Error: Incorrect Nesting

NEW INT x = 5
IF x > 10
    PRINTLN "High"
    ELSE // Syntax error! ELSE must be at same IF level
        PRINTLN "Low"
    END IF
// Correct:
IF x > 10
    PRINTLN "High"
ELSE
    PRINTLN "Low"
END IF

Error: Misunderstanding Else Execution

NEW INT value = 50
IF value > 100
    PRINTLN "Very high"
ELIF value > 75
    PRINTLN "High"
ELSE
    // This executes for ALL values <= 75, not just some
    PRINTLN "75 or below"
END IF
// Displays "75 or below"
// If you wanted more specific handling:
IF value > 100
    PRINTLN "Very high"
ELIF value > 75
    PRINTLN "High"
ELIF value > 50
    PRINTLN "Medium"
ELSE
    PRINTLN "50 or below"
END IF