Variables and Assignment
Variables are named storage locations that hold values in your program. They’re fundamental to any programming task.
Variable Declaration
Section titled “Variable Declaration”Implicit Declaration
Section titled “Implicit Declaration”Simply assign a value to create a variable:
name = "Alice"age = 30price = 19.99isActive = trueExplicit Type Declaration
Section titled “Explicit Type Declaration”Optionally specify the variable type:
number age = 30string name = "Alice"boolean isActive = truearray numbers = [1, 2, 3]Explicit types make your code more readable and help prevent type-related errors.
The define Statement
Section titled “The define Statement”Declare a variable without initializing it:
define counterdefine userNamedefine isValid
counter = 0userName = "John"isValid = trueThis is useful when you need to declare a variable before you know its value.
When to Use define
Section titled “When to Use define”// Good use case: variable will be set conditionallydefine message
if score >= 90 message = "Excellent!"else if score >= 70 message = "Good job!"else message = "Keep trying!"
output messageVariable Assignment
Section titled “Variable Assignment”Simple Assignment
Section titled “Simple Assignment”x = 5name = "Bob"isComplete = falseCopy Assignment
Section titled “Copy Assignment”Variables can be assigned the value of other variables:
original = 42copy = original // copy now equals 42
original = 100 // changing original doesn't affect copyoutput copy // still 42Multiple Assignments
Section titled “Multiple Assignments”a = 10b = 20c = 30
// Swap values using a temporary variabletemp = aa = bb = temp// Now a = 20 and b = 10Variable Naming Rules
Section titled “Variable Naming Rules”Valid Variable Names
Section titled “Valid Variable Names”age = 25firstName = "John"user_name = "alice123"totalPrice = 99.99isValid = truecount2 = 5Naming Conventions
Section titled “Naming Conventions”Camel Case (recommended):
firstName = "Alice"totalPrice = 99.99isLoggedIn = truestudentCount = 30Snake Case:
first_name = "Alice"total_price = 99.99is_logged_in = truestudent_count = 30Best Practices:
- Use descriptive names:
studentCountinstead ofsc - Start with a lowercase letter
- Use camelCase or snake_case consistently
- Avoid single-letter names except for loop counters
Invalid Names
Section titled “Invalid Names”Variables must follow specific naming rules. Here are common mistakes to avoid:
Starting with numbers:
2ndPlace = "Alice" // Invalid - starts with number1stStudent = "Bob" // Invalid - starts with number99problems = "Jay-Z" // Invalid - starts with numberUsing kebab-case (hyphens):
user-name = "Bob" // Invalid - hyphens not allowedfirst-name = "Alice" // Invalid - hyphens not allowedtotal-price = 99.99 // Invalid - hyphens not allowedis-valid = true // Invalid - hyphens not allowedUsing dots or other special characters:
first.name = "Charlie" // Invalid - dots not alloweduser@name = "Dave" // Invalid - @ not allowedtotal$ = 100 // Invalid - $ not allowedprice% = 0.15 // Invalid - % not alloweduser#id = 123 // Invalid - # not allowedSpaces in names:
first name = "Alice" // Invalid - spaces not allowedtotal price = 99.99 // Invalid - spaces not alloweduser count = 10 // Invalid - spaces not allowedStarting with special characters:
_private = "secret" // Valid, but discouraged$value = 100 // Invalid - $ not allowed#count = 5 // Invalid - # not allowed@user = "alice" // Invalid - @ not allowedReserved keywords:
if = 5 // Invalid - 'if' is a keywordwhile = 10 // Invalid - 'while' is a keywordfor = 3 // Invalid - 'for' is a keywordfunction = "test" // Invalid - 'function' is a keywordreturn = true // Invalid - 'return' is a keywordRemember: Use camelCase or snake_case, start with a letter, and avoid special characters (except underscore).
Variable Scope
Section titled “Variable Scope”Local Variables
Section titled “Local Variables”Variables defined inside functions or blocks:
function calculateTotal takes in price and quantity { subtotal = price * quantity // Local to this function tax = subtotal * 0.1 // Local to this function total = subtotal + tax // Local to this function return total}
// subtotal, tax, and total don't exist outside the functionUsing Variables
Section titled “Using Variables”// Counter variablecount = 0count = count + 1count++ // Same as above
// Accumulator variablesum = 0for i from 1 to 10 sum = sum + i
// Flag variablefound = falsefor each item in items if item equals target found = true jumpVariable Reassignment
Section titled “Variable Reassignment”Variables can be reassigned to new values:
score = 0output "Score: {score}" // 0
score = 10output "Score: {score}" // 10
score = score + 5output "Score: {score}" // 15
score++output "Score: {score}" // 16Type Changes
Section titled “Type Changes”Variables can hold different types at different times:
value = 42 // numberoutput value // 42
value = "hello" // now a stringoutput value // "hello"
value = true // now a booleanoutput value // trueNote: While this is allowed, it’s generally better to keep variables with consistent types for clarity.
Compound Assignment Operators
Section titled “Compound Assignment Operators”Shorthand for updating variables:
counter = 10
counter += 5 // counter = counter + 5 (15)counter -= 3 // counter = counter - 3 (12)counter *= 2 // counter = counter * 2 (24)counter /= 4 // counter = counter / 4 (6)counter %= 4 // counter = counter % 4 (2)counter ^= 3 // counter = counter ^ 3 (8)Increment and Decrement
Section titled “Increment and Decrement”count = 5
count++ // count = count + 1 (6)count-- // count = count - 1 (5)
// Useful in loopsfor i from 0 to 10 sum += i count++Variable Initialization
Section titled “Variable Initialization”Always Initialize
Section titled “Always Initialize”// Good: initializedsum = 0count = 0message = ""isReady = false
// Risky: uninitializeddefine totaltotal = total + 10 // Error if total has no initial valueDefault Values
Section titled “Default Values”// Numbers: start at 0count = 0sum = 0
// Strings: start as emptymessage = ""name = ""
// Booleans: start with explicit valueisActive = falseisComplete = false
// Arrays: start emptyitems = []numbers = []Common Variable Patterns
Section titled “Common Variable Patterns”Swap Variables
Section titled “Swap Variables”a = 10b = 20
temp = aa = bb = temp
output "a = {a}, b = {b}" // a = 20, b = 10Running Total
Section titled “Running Total”total = 0prices = [19.99, 29.99, 9.99, 39.99]
for each price in prices total += price
output "Total: ${total}"Counter
Section titled “Counter”positiveCount = 0numbers = [5, -3, 8, -1, 12, -7]
for each num in numbers if num > 0 positiveCount++
output "Positive numbers: {positiveCount}"Flag Variable
Section titled “Flag Variable”hasErrors = falsevalues = [5, 10, -3, 20]
for each value in values if value < 0 hasErrors = true jump
if hasErrors output "Error: negative values found"Maximum/Minimum Tracking
Section titled “Maximum/Minimum Tracking”numbers = [23, 45, 12, 67, 34]
max = numbers[0]min = numbers[0]
for each num in numbers if num > max max = num if num < min min = num
output "Max: {max}, Min: {min}"Variable Examples
Section titled “Variable Examples”Temperature Converter
Section titled “Temperature Converter”output "Enter temperature in Fahrenheit: "input fahrenheitfahrenheit = convert fahrenheit to number
celsius = (fahrenheit - 32) * 5 / 9
output "{fahrenheit}°F = {celsius}°C"Grade Calculator
Section titled “Grade Calculator”output "Enter three test scores:"input score1input score2input score3
score1 = convert score1 to numberscore2 = convert score2 to numberscore3 = convert score3 to number
total = score1 + score2 + score3average = total / 3
output "Average: {average}"
if average >= 90 output "Grade: A"else if average >= 80 output "Grade: B"else if average >= 70 output "Grade: C"else output "Grade: F"Simple Interest Calculator
Section titled “Simple Interest Calculator”output "Principal amount: "input principalprincipal = convert principal to number
output "Interest rate (as decimal, e.g., 0.05 for 5%): "input raterate = convert rate to number
output "Time in years: "input timetime = convert time to number
interest = principal * rate * timetotal = principal + interest
output "Interest: ${interest}"output "Total amount: ${total}"Best Practices
Section titled “Best Practices”-
Use meaningful names
// Badx = 30// GoodstudentAge = 30 -
Initialize before use
// Baddefine totaltotal = total + 10 // Error!// Goodtotal = 0total = total + 10 -
Keep scope minimal
// Only declare variables where neededfor i from 1 to 10temp = i * 2 // temp only exists in loopoutput temp -
Use constants for fixed values
constant TAX_RATE = 0.08constant MAX_USERS = 100price = 50tax = price * TAX_RATE -
Be consistent with naming
// Pick one style and stick with itfirstName = "Alice" // camelCaselastName = "Smith" // camelCasetotalPrice = 99.99 // camelCase