Razen Documentation

Learn how to use the Razen Programming Language.

Variables & Data Types

# Variables & Data Types Let's explore how to work with variables and data types in the Razen Programming Language. Variables are containers for storing data values, and Razen offers a variety of intuitive tokens for declaring different types of variables. ## 1. Numeric Variables & Values Numeric variables store numbers, including both integers and floating-point values. Create a new file called `numbers.rzn` and open it in your favorite text editor. Then, add the following code: ```razen # Basic integer variables declaration num integer = 16; # Integer value using the num token num count = 42; # Another integer example # Basic float variables declaration num float = 1.45; # Float value using the num token num pi = 3.14159; # Another float example # Mathematical operations num sum = integer + count; # Addition num product = integer * float; # Multiplication num power = integer ^ 2; # Exponentiation # Show statement for displaying output to the console show "This is an integer: " + integer; show "This is a float: " + float; show "Sum: " + sum; show "Product: " + product; show "Power: " + power; ``` This program demonstrates how to use the `num` token for declaring numeric variables and performing basic mathematical operations. The `show` statement is used to display the results to the console. ### Running Your Program To run your program, open a terminal or command prompt, navigate to the directory containing your `numbers.rzn` file, and run: ```bash razen-run numbers.rzn ``` You should see the following output: ``` This is an integer: 16 This is a float: 1.45 Sum: 58 Product: 23.2 Power: 256 ``` ### Understanding the Code Let's break down what's happening in this `numbers.rzn` program: 1. **Comments** ```razen # Basic integer variables declaration ``` Comments start with the `#` symbol and are ignored by the Razen compiler. They're useful for adding notes and explanations to your code. 2. **Integer Declaration** ```razen num integer = 16; ``` This line declares a variable named `integer` and assigns it the value `16`. The `num` token is used to specify that this is a numeric variable. 3. **Float Declaration** ```razen num float = 1.45; ``` This line declares a variable named `float` and assigns it the floating-point value `1.45`. Notice that the same `num` token is used for both integers and floats. 4. **Mathematical Operations** ```razen num sum = integer + count; # Addition num product = integer * float; # Multiplication num power = integer ^ 2; # Exponentiation ``` Razen supports standard mathematical operations like addition (`+`), subtraction (`-`), multiplication (`*`), division (`/`), and exponentiation (`^`). 5. **Output Display** ```razen show "This is an integer: " + integer; ``` The `show` statement outputs text to the console. Here, we're concatenating a string with the value of the `integer` variable using the `+` operator. ## 2. String Variables & Values String variables store text data. Create a new file called `strings.rzn` and open it in your favorite text editor. Then, add the following code: ```razen # Basic string variables declaration str first_name = "Prathmesh"; # str token is used for string variables str last_name = "Barot"; # Another string variable # String concatenation (joining strings) str full_name = first_name + " " + last_name; # String methods str uppercase_name = StrLib[upper](full_name); str first_initial = StrLib[substring](first_name, 0, 1); # String formatting str greeting = "Hello, {first_name}!"; # Using string interpolation str message = format("Welcome, {0} {1}!", first_name, last_name); # Using format function # Show statement for displaying output show "Hello, " + first_name + " " + last_name + "!"; show "Full name: " + full_name; show "Uppercase: " + uppercase_name; show "First initial: " + first_initial; show "Greeting: " + greeting; show "Message: " + message; ``` This program demonstrates how to use the `str` token for declaring string variables and performing various string operations. Strings in Razen can be manipulated using built-in methods and formatted using interpolation or the `format` function. ### Running Your Program To run your program, open a terminal or command prompt, navigate to the directory containing your `strings.rzn` file, and run: ```bash razen-run strings.rzn ``` You should see the following output: ``` Hello, Prathmesh Barot! Full name: Prathmesh Barot Uppercase: PRATHMESH BAROT First initial: P Greeting: Hello, Prathmesh! Message: Welcome, Prathmesh Barot! ``` ### Understanding the Code Let's break down what's happening in this `strings.rzn` program: 1. **String Declaration** ```razen str first_name = "Prathmesh"; str last_name = "Barot"; ``` These lines declare string variables using the `str` token. String values are enclosed in double quotes. 2. **String Concatenation** ```razen str full_name = first_name + " " + last_name; ``` The `+` operator joins (concatenates) strings together. Here, we're combining the first name, a space, and the last name. 3. **String Methods** ```razen str uppercase_name = StrLib[upper](full_name); str first_initial = StrLib[substring](first_name, 0, 1); ``` Razen provides built-in library functions for manipulating strings. The `StrLib[upper]()` function converts all characters to uppercase, while `StrLib[substring](str, start, end)` extracts a portion of the string. 4. **String Formatting** ```razen str greeting = "Hello, {first_name}!"; str message = format("Welcome, {0} {1}!", first_name, last_name); ``` Razen supports string interpolation using curly braces `{}` and the `format()` function for more complex formatting. 5. **Output Display** ```razen show "Hello, " + first_name + " " + last_name + "!"; ``` This displays the concatenated string in the console. ## 3. Boolean Variables & Conditional Statements Boolean variables store logical values (`true`, `false`, or `null`). They're essential for controlling program flow through conditional statements. Create a new file called `booleans.rzn` and add the following code: ```razen # Basic boolean variables declaration bool isActive = true; # bool token with true value bool isFail = false; # bool token with false value bool isVoid = null; # bool token with null value # Logical operations bool isLoggedIn = true; bool hasPermission = false; bool canAccess = isLoggedIn and hasPermission; # Logical AND bool canView = isLoggedIn or hasPermission; # Logical OR bool isRestricted = not isLoggedIn; # Logical NOT # Comparison operations num score = 85; bool isPassing = score >= 70; # Greater than or equal bool isExcellent = score > 90; # Greater than bool isAverage = score is 85; # Equality check bool needsImprovement = score < 60; # Less than # Conditional statements with boolean variables if (isActive) { show "User is Active!"; # Executes when isActive is true } else { show "User is Inactive"; # Executes when isActive is false } if (isFail) { show "Student is Fail"; # Executes when isFail is true } else { show "Student is Pass"; # Executes when isFail is false } if (isVoid) { show "Nothing"; # Executes when isVoid is not null } else { show "Here is a void!"; # Executes when isVoid is null } # Complex conditions if (isActive and not isFail) { show "Active and passing!"; # Combined conditions } # Conditional expression (ternary operator) str status = isActive ? "ONLINE" : "OFFLINE"; # Compact conditional assignment show "User status: " + status; ``` ### Running Your Program To run your program, open a terminal or command prompt, navigate to the directory containing your `booleans.rzn` file, and run: ```bash razen-run booleans.rzn ``` You should see the following output: ``` User is Active! Student is Pass Here is a void! Active and passing! User status: ONLINE ``` ### Understanding the Code Let's break down what's happening in this `booleans.rzn` program: 1. **Boolean Declaration** ```razen bool isActive = true; bool isFail = false; bool isVoid = null; ``` These lines declare boolean variables using the `bool` token. Boolean values can be `true`, `false`, or `null`. 2. **Logical Operations** ```razen bool canAccess = isLoggedIn and hasPermission; # Logical AND bool canView = isLoggedIn or hasPermission; # Logical OR bool isRestricted = not isLoggedIn; # Logical NOT ``` Razen supports standard logical operations: - `and`: Both conditions must be true - `or`: At least one condition must be true - `not`: Inverts the boolean value 3. **Comparison Operations** ```razen bool isPassing = score >= 70; # Greater than or equal bool isExcellent = score > 90; # Greater than bool isAverage = score is 85; # Equality check bool needsImprovement = score < 60; # Less than ``` Comparison operators create boolean values by comparing values. 4. **Conditional Statements** ```razen if (isActive) { show "User is Active!"; } else { show "User is Inactive"; } ``` The `if` statement executes code blocks based on boolean conditions: - The code inside the `if` block runs when the condition is `true` - The code inside the `else` block runs when the condition is `false` 5. **Complex Conditions** ```razen if (isActive and not isFail) { show "Active and passing!"; } ``` Multiple conditions can be combined using logical operators. 6. **Conditional Expression (Ternary Operator)** ```razen str status = isActive ? "ONLINE" : "OFFLINE"; ``` This is a compact way to assign values based on a condition. If `isActive` is true, `status` becomes "ONLINE", otherwise it becomes "OFFLINE". ## 4. Constant Variables Constants are variables whose values cannot be changed after initialization. They're useful for values that should remain fixed throughout your program. Create a new file called `constants.rzn` and add the following code: ```razen # Declaring constants const PI = 3.14159; const MAX_USERS = 100; const APP_NAME = "Razen Demo"; const IS_PRODUCTION = false; # Using constants num radius = 5; num area = PI * (radius ^ 2); show "Application: " + APP_NAME; show "Circle area: " + area; show "Max users: " + MAX_USERS; show "Production mode: " + IS_PRODUCTION; # This would cause an error: # PI = 3.14; # Cannot reassign a constant ``` ### Running Your Program To run your program, open a terminal or command prompt, navigate to the directory containing your `constants.rzn` file, and run: ```bash razen-run constants.rzn ``` You should see the following output: ``` Application: Razen Demo Circle area: 78.53975 Max users: 100 Production mode: false ``` ### Understanding the Code 1. **Constant Declaration** ```razen const PI = 3.14159; const MAX_USERS = 100; const APP_NAME = "Razen Demo"; const IS_PRODUCTION = false; ``` Constants are declared using the `const` token. By convention, constant names are often written in UPPERCASE with underscores separating words. 2. **Using Constants** ```razen num area = PI * (radius ^ 2); ``` Constants can be used just like variables, but their values cannot be changed after initialization. ## 5. Variable Scope and Lifetime Variable scope determines where in your code a variable can be accessed. Create a new file called `scope.rzn` and add the following code: ```razen # Global scope variable num globalCounter = 0; # Function with local variables fun incrementCounter(num amount) { # Local variable only accessible within this function num oldValue = globalCounter; # Modify global variable globalCounter = globalCounter + amount; # Block scope with its own variables if (amount > 0) { # This variable only exists within this if block str message = "Counter increased"; show message + " from " + oldValue + " to " + globalCounter; } # This would cause an error because message is out of scope # show message; return globalCounter; } # Using the function and global variable show "Initial counter: " + globalCounter; num result = incrementCounter(5); show "Final counter: " + result; # Using box for temporary variables with automatic cleanup with box tempData = "This is temporary" { show "Inside box: " + tempData; # Process with tempData } # tempData is no longer accessible here ``` ### Running Your Program To run your program, open a terminal or command prompt, navigate to the directory containing your `scope.rzn` file, and run: ```bash razen-run scope.rzn ``` You should see the following output: ``` Initial counter: 0 Counter increased from 0 to 5 Final counter: 5 Inside box: This is temporary ``` ### Understanding the Code 1. **Global Scope** ```razen num globalCounter = 0; ``` Variables declared outside any function or block have global scope and can be accessed from anywhere in the program. 2. **Function Scope** ```razen fun incrementCounter(num amount) { num oldValue = globalCounter; # ... } ``` Variables declared inside a function (including parameters) have function scope and are only accessible within that function. 3. **Block Scope** ```razen if (amount > 0) { str message = "Counter increased"; # ... } ``` Variables declared inside a block (like an if statement) have block scope and are only accessible within that block. 4. **Temporary Variables with Box** ```razen with box tempData = "This is temporary" { # Use tempData here } # tempData is no longer accessible ``` The `box` token with a `with` block creates variables that are automatically cleaned up when execution leaves the block. ## Next Steps Now that you understand variables and data types in Razen, you're ready to explore more advanced topics. Check out these guides to continue your journey: - **[Control Structures](/docs/language-basics/control_structures.mdx)** - Learn about loops and conditional statements - **[Functions](/docs/language-basics/functions.mdx)** - Discover how to create reusable code blocks - **[Collections →](/docs/language-basics/collections.mdx)** - Explore lists, arrays, and maps