UNEL โ The Complete Textbook
Universal Natural English Language
By K N S Jaya Ram Reddy
Programming in Plain English
Version 1.0 โ First Edition
Written for language learners, computer science students, and professionals
"The best programming language is one that reads like a book."
Table of Contents
| Chapter | Title | Page |
|---|---|---|
| 1 | Statements | Introduction, I/O, Variables, Strings, Numbers |
| 2 | Expressions | Playground, Type Conversion, Math, Formatting |
| 3 | Objects | Strings Revisited, Variables Revisited, Lists, Tuples |
| 4 | Decisional / Conditional Statements | Booleans, If-Else, Logic, Nesting |
| 5 | Loops | While, For, Nested Loops, Break/Continue |
| 6 | Functions | Defining, Scope, Parameters, Return Values |
| 7 | Modules | Module Basics, Importing, Finding Modules |
| 8 | Strings | Operations, Slicing, Searching, Formatting |
| 9 | Lists | Modifying, Sorting, Operations, Comprehensions |
| 10 | Dictionaries | Basics, Creation, Operations, Looping |
| 11 | Classes | OOP Basics, Instances, Methods, Overloading |
| 12 | Recursion | Basics, Math, Strings & Lists, Problem Solving |
| 13 | Inheritance | Basics, Attributes, Methods, Hierarchies |
| 14 | Files and Exceptions | Reading, Writing, Handling, Raising |
| 15 | Libraries | Standard Library, Built-in Functions |
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Chapter 1: Statements
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
1.1 Introduction and Background
What is UNEL?
Definition: UNEL (Universal Natural English Language) is a programming language in which the syntax IS English grammar, allowing code to read like natural instructions.
UNEL stands for Universal Natural English Language. It is a programming language in which the syntax IS English grammar. Every line of UNEL reads like a sentence from a book. There are no semicolons, no curly braces, and no cryptic symbols. Instead, you write code the same way you would write instructions for a person.
The Core Principle
Definition: The core principle of UNEL states that if you can say it in English, you can code it in UNEL โ every statement reads like a sentence from a book.
UNEL's golden rule: If you can say it in English, you can code it in UNEL.
In traditional programming languages, you write:
x = 10;
if (x > 5) {
printf("Big number");
}
In UNEL, you write:
Set count to 10.
If count is greater than 5:
Display "Big number".
End if.
Output:
Big number
The UNEL version reads like an instruction you would give to another person. This is not a coincidence โ it is the foundation of the entire language.
History and Philosophy
Definition: UNEL was created with the philosophy that programming should look like natural language rather than mathematical notation, replacing cryptic symbols with plain English words.
UNEL was created with one question in mind: Why should programming look like mathematics when most people think in words?
Traditional languages borrowed their syntax from mathematics and engineering โ symbols like {, }, ;, &&, ||, !=. These are efficient for machines but unnatural for humans. UNEL replaces all of them with plain English:
| Concept | Traditional | UNEL |
|---|---|---|
| Assign a variable | x = 5 |
Set x to 5. |
| Print output | print("Hello") |
Display "Hello". |
| Compare values | if (x > 10) |
If x is greater than 10: |
| Loop through items | for item in list: |
For each item in list: |
| Define a function | def add(a, b): |
Define function add that takes a and b: |
| Write a comment | # comment |
Note: comment |
| End a statement | ; |
. (period) |
Five Core Rules of UNEL
Definition: The five core rules of UNEL define the fundamental syntax conventions: periods end statements, colons start blocks, Note marks comments, keywords are case-insensitive, and indentation is recommended.
- Every statement ends with a period (
.) โ just like a sentence. - Blocks start with a colon (
:) and end withEndkeywords. - Comments start with
Note:โ like margin notes in a textbook. - Keywords are case-insensitive โ
Display,display, andDISPLAYall work. - Indentation is recommended but not required. Code should be readable.
Your Very First UNEL Program
Definition: A first program in UNEL demonstrates that a single English sentence with a period is all that is needed to produce output.
Display "Hello, World!".
Output:
Hello, World!
That's it. One sentence. One period. Let us break it down:
Displayโ the keyword that tells UNEL to show output on the screen."Hello, World!"โ the text you want to display, enclosed in double quotes..โ the period that ends the statement (like ending a sentence).
Output:
Hello, World!
A Slightly Bigger Program
Definition: A slightly bigger program combines multiple UNEL statements โ output, variables, and calculations โ to demonstrate how statements work together as instructions.
Note: This is my first UNEL program.
Note: It introduces itself and calculates a sum.
Display "Welcome to UNEL!".
Display "Programming in plain English.".
Display "".
Set first to 10.
Set second to 20.
Set total to first plus second.
Display "The sum of " plus first plus " and " plus second plus " is " plus total plus ".".
Output:
Welcome to UNEL!
Programming in plain English.
The sum of 10 and 20 is 30.
Read the code aloud. It sounds like instructions you would write for a friend.
1.2 Input and Output
Output โ The Display Statement
Definition: The Display statement is UNEL's command for showing information to the user, equivalent to print() in Python or printf() in C.
Display is how UNEL shows information to the user. It is equivalent to print() in Python, printf() in C, or System.out.println() in Java.
Display "Hello".
Display "UNEL is fun".
Display 42.
Display true.
Output:
Hello
UNEL is fun
42
true
UNEL also accepts these synonyms for Display:
| Keyword | Example |
|---|---|
Display |
Display "Hello". |
Show |
Show "Hello". |
Print |
Print "Hello". |
Say |
Say "Hello". |
Output |
Output "Hello". |
All five produce the same result. Use whichever reads most naturally in your sentence.
Displaying Multiple Values
Definition: Displaying multiple values involves using the plus operator to concatenate strings and variables into a single output line.
You can join values together using the plus keyword:
Set name to "Alice".
Set age to 25.
Display "My name is " plus name plus " and I am " plus age plus " years old.".
Output: My name is Alice and I am 25 years old.
Displaying Blank Lines
Definition: Displaying blank lines uses Display with an empty string to create visual spacing in program output.
Display "Line one".
Display "".
Display "Line three".
Output:
Line one
Line three
Input โ The Ask Statement
Definition: The Ask statement is UNEL's command for receiving input from the user, storing the response in a named variable.
Ask is how UNEL receives input from the user. It reads like a natural question:
Ask "What is your name? " and store in name.
Display "Hello, " plus name plus "!".
How it works:
1. Ask โ prompts the user with the message "What is your name? "
2. and store in name โ saves whatever the user types into the variable name
Important: All Input is Text
Definition: All input received through the Ask statement is stored as text (string), requiring explicit type conversion before it can be used in mathematical calculations.
When a user types something, UNEL receives it as text (a string). If you need to use it as a number, you must convert it:
Ask "Enter your age: " and store in age.
Convert age to a number.
Set birth_year to 2026 minus age.
Display "You were born around " plus birth_year plus ".".
Without the Convert age to a number. line, 2026 minus age would fail because you cannot subtract text from a number.
Complete Input/Output Example
Definition: A complete input/output example demonstrates the full cycle of asking the user for data, processing it, and displaying the result.
Note: A personal greeting program.
Ask "What is your name? " and store in name.
Ask "What is your favorite color? " and store in color.
Display "".
Display "Hello, " plus name plus "!".
Display "Great choice โ " plus color plus " is a wonderful color.".
Sample Run:
What is your name? Jayaram
What is your favorite color? Blue
Hello, Jayaram!
Great choice โ Blue is a wonderful color.
1.3 Variables
Definition: A variable is a named container used to store a value in memory. It allows a program to store, retrieve, and modify data during execution.
Explanation: Each variable has a name (identifier) and holds a value such as a number, text, or boolean. The value of a variable can change over time.
What is a Variable?
Definition: A variable is a named container that holds a value, acting as a labeled box where the label is the name and the contents are the stored value.
A variable is a named container that holds a value. Think of it as a labeled box:
- The label is the variable name (e.g.,
age,name,score) - The contents are the value inside (e.g.,
25,"Alice",95)
Creating Variables with Set
Definition: The Set statement is the primary way to create and assign values to variables in UNEL, reading naturally as 'Set name to value.'
The most common way to create a variable in UNEL:
Set age to 25.
Set name to "Alice".
Set price to 19.99.
Set is_student to true.
Read these aloud: "Set age to 25." "Set name to Alice." They read like natural instructions.
Variable Naming Rules
Definition: Variable naming rules specify that names must start with a letter or underscore, can contain letters, digits, and underscores, and should be descriptive.
- Names can contain letters, digits, and underscores
- Names must start with a letter or underscore
- Names are case-sensitive (
ageandAgeare different) - Use descriptive names โ
student_nameis better thansn
Good variable names:
Set student_name to "Jayaram".
Set total_marks to 450.
Set is_passed to true.
Set average_score to 75.5.
Avoid:
Set x to "Jayaram". Note: Too vague โ what does x mean?
Set a to 450. Note: Too short โ what does a represent?
Changing Variable Values
Definition: Changing variable values allows reassigning a variable to a new value at any time using the Set statement, overwriting the previous value.
You can change a variable's value at any time:
Set score to 80.
Display "Score is: " plus score.
Set score to 95.
Display "Score is now: " plus score.
Output:
Score is: 80
Score is now: 95
Constants โ Values That Never Change
Definition: Constants are variables whose values cannot be changed after assignment, declared using the Constant keyword to protect important fixed values.
If you want a value that cannot be modified, use Constant:
Constant PI is 3.14159.
Constant MAX_SCORE is 100.
Constant APP_NAME is "My Calculator".
Display "Pi is " plus PI.
Display "Maximum score is " plus MAX_SCORE.
Output:
Pi is 3.14159
Maximum score is 100
Attempting to change a constant will cause an error:
Constant PI is 3.14159.
Set PI to 3.14. Note: ERROR! Cannot reassign constant 'PI'.
Increase and Decrease
Definition: The Increase and Decrease statements modify numeric variables by adding to or subtracting from their current value using natural English syntax.
UNEL provides natural English for incrementing and decrementing:
Set counter to 0.
Display "Counter: " plus counter.
Increase counter by 1.
Display "After increase by 1: " plus counter.
Increase counter by 5.
Display "After increase by 5: " plus counter.
Decrease counter by 2.
Display "After decrease by 2: " plus counter.
Output:
Counter: 0
After increase by 1: 1
After increase by 5: 6
After decrease by 2: 4
Swapping Two Variables
Definition: The Swap statement exchanges the values of two variables in a single, readable English command.
Set left to 10.
Set right to 20.
Display "Before: left = " plus left plus ", right = " plus right.
Swap left and right.
Display "After: left = " plus left plus ", right = " plus right.
Output:
Before: x = 10, y = 20
After: x = 20, y = 10
1.4 String Basics
Definition: A string is a sequence of characters enclosed in double quotes, used to represent text in a program.
Explanation: Strings can contain letters, numbers, spaces, and symbols. They are used for displaying messages, storing text data, and performing text operations.
What is a String?
Definition: A string is a sequence of characters enclosed in double quotes, used to represent and manipulate text data in a program.
A string (called "Text" in UNEL) is a sequence of characters โ letters, numbers, spaces, and symbols โ enclosed in double quotes.
Set greeting to "Hello, World!".
Set empty to "".
Set sentence to "UNEL makes coding easy.".
Set with_numbers to "I have 3 cats.".
String Concatenation (Joining Strings)
Definition: String concatenation joins two or more strings together using the plus operator to create a combined text value.
Use plus to join strings together:
Set first to "Hello".
Set second to "World".
Set message to first plus ", " plus second plus "!".
Display message.
Output: Hello, World!
String Length
Definition: The length() function returns the number of characters in a string, counting all letters, spaces, and symbols.
Set message to "UNEL".
Display "The word '" plus message plus "' has " plus length(message) plus " characters.".
Output: The word 'UNEL' has 4 characters.
String Interpolation
Definition: String interpolation in depth shows advanced usage of curly braces {} to embed complex expressions and multiple variables within formatted strings.
You can embed expressions directly inside strings using curly braces {}:
Set name to "Alice".
Set score to 95.
Display "Student {name} scored {score} marks.".
Output: Student Alice scored 95 marks.
Escape Characters
Definition: Escape characters are special sequences within strings that represent characters like newlines, tabs, or quotes that cannot be typed directly.
To include special characters inside a string:
Display "She said, \"Hello!\"". Note: \" for double quote inside
Display "First line.\nSecond line.". Note: \n for new line
Display "Column1\tColumn2". Note: \t for tab
Output:
\" for double quote inside
First line.\nSecond line.
Column1\tColumn2
Simple String Operations
Definition: Simple string operations include basic functions like length(), uppercase(), lowercase(), and reverse() that transform or inspect text values.
Set message to "Hello, World!".
Display uppercase(message).
Display lowercase(message).
Display length(message).
Display contains(message, "World").
Display replace(message, "World", "UNEL").
Output:
HELLO, WORLD!
hello, world!
13
true
Hello, UNEL!
1.5 Number Basics
Definition: A number is a data type used to represent numeric values in a program, including integers (whole numbers) and decimals (floating-point numbers).
Explanation: Numbers are used for calculations, comparisons, and measurements. UNEL supports both positive and negative values, as well as decimal numbers for precision.
Integers โ Whole Numbers
Definition: Integers are whole numbers without decimal points, used for counting, indexing, and calculations that require exact whole values.
Integers are whole numbers (positive, negative, or zero) with no decimal point:
Set age to 25.
Set temperature to -5.
Set count to 0.
Set population to 1400000000.
Display "Age: " plus age.
Display "Temperature: " plus temperature.
Display "Count: " plus count.
Display "Population: " plus population.
Output:
Age: 25
Temperature: -5
Count: 0
Population: 1400000000
Decimals โ Floating-Point Numbers
Definition: Decimals (floating-point numbers) represent values with fractional parts, used for measurements, percentages, and calculations requiring precision.
Decimals are numbers with a fractional part:
Set pi to 3.14159.
Set price to 29.99.
Set rate to 0.085.
Set negative to -2.5.
Display "Pi: " plus pi.
Display "Price: " plus price.
Display "Rate: " plus rate.
Output:
Pi: 3.14159
Price: 29.99
Rate: 0.085
Arithmetic Operations
Definition: Arithmetic operations are mathematical calculations performed on numbers using English words like plus, minus, multiplied by, and divided by.
UNEL uses English words for arithmetic, making code read like a sentence:
Set first_number to 15.
Set second_number to 4.
Set sum_result to first_number plus second_number.
Display first_number plus " plus " plus second_number plus " equals " plus sum_result.
Set difference to first_number minus second_number.
Display first_number plus " minus " plus second_number plus " equals " plus difference.
Set product to first_number multiplied by second_number.
Display first_number plus " multiplied by " plus second_number plus " equals " plus product.
Set quotient to first_number divided by second_number.
Display first_number plus " divided by " plus second_number plus " equals " plus quotient.
Set remainder to mod(first_number, second_number).
Display "The remainder of " plus first_number plus " divided by " plus second_number plus " is " plus remainder.
Output:
15 plus 4 equals 19
15 minus 4 equals 11
15 multiplied by 4 equals 60
15 divided by 4 equals 3.75
The remainder of 15 divided by 4 is 3
Order of Operations
Definition: Order of operations defines the precedence rules for evaluating mathematical expressions: parentheses first, then multiplication/division, then addition/subtraction.
UNEL follows standard mathematical precedence (BODMAS / PEMDAS):
- Parentheses
( ) - Exponentiation
** - Multiplication, Division, Modulo
- Addition, Subtraction
Use parentheses to control the order:
Set result1 to 5 plus 3 multiplied by 2. Note: = 11 (multiplication first)
Set result2 to (5 plus 3) multiplied by 2. Note: = 16 (parentheses first)
Display "5 + 3 * 2 = " plus result1.
Display "(5 + 3) * 2 = " plus result2.
Output:
5 + 3 * 2 = 11
(5 + 3) * 2 = 16
Useful Math Functions
Definition: Useful math functions are built-in operations like abs(), round(), max(), min(), power(), and sqrt() that perform common mathematical calculations.
Display "Absolute value: " plus abs(-7).
Display "Square root: " plus sqrt(25).
Display "Power: " plus power(2, 10).
Display "Round: " plus round(3.14159, 2).
Display "Floor: " plus floor(3.7).
Display "Ceiling: " plus ceil(3.2).
Output:
Absolute value: 7
Square root: 5.0
Power: 1024
Round: 3.14
Floor: 3
Ceiling: 4
1.6 Error Messages
Definition: Error messages are system-generated notifications that indicate a problem in a program, explaining what went wrong and where the issue occurred.
Explanation: They help programmers identify and fix mistakes such as invalid operations, missing variables, or incorrect syntax. Understanding error messages is essential for debugging.
Understanding Errors
Definition: Understanding errors involves recognizing and interpreting the messages UNEL produces when it encounters problems in a program.
When UNEL encounters a problem, it tells you exactly what went wrong and where. Understanding error messages is essential for debugging.
Common Error Types
Definition: Common error types include undeclared variables, type mismatches, division by zero, and syntax errors โ each producing a descriptive error message.
1. Variable Not Declared
Display x.
Error: Variable 'x' has not been declared.
Fix: You must Set x to ... before using x.
2. Cannot Convert to Number
Note: ERROR demo โ this will cause an error.
Set message to "hello".
Convert txt to a number.
Error: Cannot convert to integer.
Fix: The text "hello" is not a valid number. Only numeric text like "42" can be converted.
3. Division by Zero
Set result to 10 divided by 0.
Error: Division by zero.
Fix: Always check that the divisor is not zero before dividing.
4. List Index Out of Range
Set items to ["a", "b", "c"].
Display items[5].
Error: List index 5 out of range. List has 3 items.
Fix: UNEL uses 1-based indexing. Valid indices for this list are 1, 2, and 3.
5. Cannot Reassign Constant
Constant PI is 3.14159.
Set PI to 3.14.
Error: Cannot reassign constant 'PI'.
Fix: Constants are immutable. Use a regular variable if you need to change the value.
6. Function Not Defined
Set result to calculate(5).
Error: Function 'calculate' has not been defined.
Fix: Define the function before calling it.
Using Try-Catch for Errors
Definition: The Try-Catch construct provides structured error handling, allowing programs to attempt risky operations and gracefully handle any errors that occur.
You can handle errors gracefully using Try and Catch:
Try:
Set result to 10 divided by 0.
Display result.
Catch error:
Display "Something went wrong: " plus error.
End try.
Display "Program continues normally.".
Output:
Something went wrong: Division by zero.
Program continues normally.
1.7 Comments
Definition: Comments are non-executable statements used to explain, describe, or document parts of a program for better understanding.
Explanation: Comments are ignored by the interpreter and do not affect program execution. They are useful for clarifying logic, adding notes, and organizing code.
Writing Comments with Note
Definition: The Note keyword begins a comment line in UNEL, providing a natural English way to annotate and document code.
In UNEL, comments start with Note:. Everything after Note: on that line is ignored by the compiler. Comments are like margin notes in a textbook โ they explain your thinking.
Note: This program calculates the area of a circle.
Note: Formula: area = ฯ ร rยฒ
Constant PI is 3.14159.
Set radius to 7.
Note: Calculate the area using the formula.
Set area to PI multiplied by radius multiplied by radius.
Display "The area of a circle with radius " plus radius plus " is " plus area plus ".".
Output:
The area of a circle with radius 7 is 153.93791.
When to Use Comments
Definition: Comments should be used to explain complex logic, document function purposes, and provide context โ but not to restate what the code already clearly says.
Use comments to explain WHY, not WHAT:
Note: GOOD โ explains the reasoning.
Note: Using 9.8 as gravity because we are near sea level.
Set gravity to 9.8.
Note: BAD โ states the obvious.
Note: Setting gravity to 9.8.
Set gravity to 9.8.
Use comments to separate sections:
Note: โโโ Input Section โโโ
Ask "Enter your name: " and store in name.
Ask "Enter your age: " and store in age.
Convert age to a number.
Note: โโโ Processing Section โโโ
Set birth_year to 2026 minus age.
Note: โโโ Output Section โโโ
Display "Hello, " plus name plus "! You were born around " plus birth_year plus ".".
Comments Do Not Execute
Definition: Comments are completely ignored by the interpreter and have no effect on program execution, serving only as documentation for human readers.
Note: Display "This will NOT appear on screen.".
Display "This WILL appear on screen.".
Output: This WILL appear on screen.
1.8 Why UNEL?
Definition: UNEL exists because programming should be accessible to everyone, regardless of their mathematical background, by using the language humans already know โ English.
Problem with Traditional Languages
Definition: Traditional programming languages use cryptic symbols and mathematical syntax that create unnecessary barriers for beginners and non-technical users.
Consider a simple task: Ask a user for two numbers, add them, and show the result.
In C:
#include <stdio.h>
int main() {
int a, b;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
printf("Sum: %d\n", a + b);
return 0;
}
In Python:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(f"Sum: {a + b}")
In UNEL:
Ask "Enter first number: " and store in a.
Ask "Enter second number: " and store in b.
Convert a to a number.
Convert b to a number.
Display "Sum: " plus (a plus b).
Sample Run:
Enter first number: 10
Enter second number: 20
Sum: 30
The UNEL version reads like instructions you would write for a person. No scanf, no %d, no int() casting, no f-strings. Just plain English.
Who is UNEL For?
Definition: UNEL is designed for language learners, computer science students, educators, and professionals who want to learn programming concepts through natural English.
| Audience | Why UNEL Works |
|---|---|
| Beginners | No need to memorize symbols โ just write in English |
| Students | Focus on logic and problem-solving, not syntax |
| Teachers | Students can read and understand code immediately |
| Non-programmers | Business people, designers can write simple programs |
| Professionals | Rapid prototyping and readable documentation |
UNEL is a Real Language
Definition: UNEL is a fully functional programming language with a complete compiler, interpreter, and virtual machine โ not just pseudocode or a teaching tool.
UNEL is not a toy. It supports: - Variables, constants, and all data types - If/else, switch/match, loops (while, for, repeat) - Functions with parameters, return values, and default arguments - Lists, dictionaries, tuples, and sets - Object-oriented programming (shapes, methods, inheritance) - Error handling (try/catch/throw) - Modules and imports - Lambda expressions and higher-order functions - File I/O, regular expressions, and more - A bytecode compiler and virtual machine for fast execution
1.9 Chapter Summary
Definition: The chapter summary consolidates all concepts covered, providing a quick reference of key UNEL features including I/O, variables, strings, numbers, errors, and comments.
| Concept | Syntax | Example |
|---|---|---|
| Output | Display expression. |
Display "Hello". |
| Input | Ask "prompt" and store in var. |
Ask "Name? " and store in name. |
| Variable | Set name to value. |
Set age to 25. |
| Constant | Constant NAME is value. |
Constant PI is 3.14. |
| String | "text in double quotes" |
Set msg to "Hi". |
| Integer | Whole number | Set x to 42. |
| Decimal | Number with decimal point | Set pi to 3.14. |
| Increment | Increase var by amount. |
Increase score by 10. |
| Decrement | Decrease var by amount. |
Decrease lives by 1. |
| Swap | Swap a and b. |
Swap x and y. |
| Comment | Note: text |
Note: This is a comment. |
| Statement ending | Period (.) |
Every statement ends with . |
Practice Programs
Definition: Practice programs are hands-on coding exercises that reinforce the concepts learned in the chapter through practical application.
Program 1: Display a personal introduction.
Set name to "Jayaram".
Set college to "University of Technology".
Set year to 3.
Display name plus " is a year " plus year plus " student at " plus college plus ".".
Output:
Jayaram is a year 3 student at University of Technology.
Program 2: Calculate daily wage from monthly salary.
Set monthly_salary to 30000.
Set daily_wage to monthly_salary divided by 30.
Display "Monthly salary: โน" plus monthly_salary.
Display "Daily wage: โน" plus daily_wage.
Output:
Monthly salary: โน30000
Daily wage: โน1000
Program 3: Convert kilometers to miles.
Set km to 100.
Set miles to km multiplied by 0.621371.
Display km plus " kilometers = " plus round(miles, 2) plus " miles.".
Output:
100 kilometers = 62.14 miles.
๐ Try It Yourself โ Interactive Programs
Definition: Interactive programs are input-based exercises using the Ask statement that allow learners to practice building dynamic, user-driven applications.
Program 4: Personal introduction (input-based).
Ask "What is your name? " and store in name.
Ask "How old are you? " and store in age.
Ask "What city do you live in? " and store in city.
Display "".
Display "Hello, " plus name plus "!".
Display "You are " plus age plus " years old and live in " plus city plus ".".
Sample Run:
What is your name? Jayaram
How old are you? 21
What city do you live in? Hyderabad
Hello, Jayaram!
You are 21 years old and live in Hyderabad.
Program 5: Simple calculator (input-based).
Ask "Enter first number: " and store in a.
Ask "Enter second number: " and store in b.
Convert a to a number.
Convert b to a number.
Display "".
Display a plus " + " plus b plus " = " plus (a plus b).
Display a plus " - " plus b plus " = " plus (a minus b).
Display a plus " ร " plus b plus " = " plus (a multiplied by b).
Display a plus " รท " plus b plus " = " plus (a divided by b).
Sample Run:
Enter first number: 15
Enter second number: 4
15 + 4 = 19
15 - 4 = 11
15 ร 4 = 60
15 รท 4 = 3.75
Program 6: Temperature converter (input-based).
Ask "Enter temperature in Celsius: " and store in celsius.
Convert celsius to a number.
Set fahrenheit to (celsius multiplied by 9 divided by 5) plus 32.
Display celsius plus "ยฐC = " plus fahrenheit plus "ยฐF".
Sample Run:
Enter temperature in Celsius: 37
37ยฐC = 98.6ยฐF
Program 7: Area of a circle (input-based).
Constant PI is 3.14159.
Ask "Enter the radius: " and store in radius.
Convert radius to a number.
Set area to PI multiplied by radius multiplied by radius.
Set circumference to 2 multiplied by PI multiplied by radius.
Display "Radius: " plus radius.
Display "Area: " plus round(area, 2).
Display "Circumference: " plus round(circumference, 2).
Sample Run:
Enter the radius: 7
Radius: 7
Area: 153.94
Circumference: 43.98
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Chapter 2: Expressions
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
2.1 The UNEL Playground
Definition: The UNEL Playground is an interactive web-based environment where users can write, run, and experiment with UNEL code directly in their browser.
What is the Playground?
Definition: The Playground is UNEL's online code editor that provides instant execution, syntax highlighting, and output display without any installation.
The UNEL Playground is a web-based development environment where you can write, run, and test UNEL programs directly in your browser. No installation needed.
How to Access
Definition: The Playground is accessed through a web browser by navigating to the UNEL project's hosted URL.
- Start the UNEL server:
python3 playground.py - Open your browser and navigate to
http://localhost:5001 - You will see: the code editor on the left, output panel on the right, and example programs in the sidebar.
Playground Features
Definition: Playground features include a code editor with syntax highlighting, output panel, engine selection (interpreter/VM), and example programs.
| Feature | Description |
|---|---|
| Editor | Syntax highlighting, line numbers, auto-indent |
| Run Button | Execute your program with one click |
| Output Panel | See results, errors, and interactive input |
| Examples | Click any example to load it instantly |
| Engine Toggle | Switch between Tree-Walker and Bytecode VM |
| Copy / Save | Copy or save your code |
Your First Playground Session
Definition: A first playground session demonstrates writing and running a simple UNEL program in the web-based editor.
- Open the playground
- Clear the editor
- Type:
Display "Hello from the Playground!". - Click โถ Run
- See the output:
Hello from the Playground!
Writing Multi-Line Programs
Definition: Multi-line programs in the Playground allow writing complete applications with variables, calculations, and output across multiple lines.
Note: BMI Calculator.
Set weight to 70.
Set height to 1.75.
Set bmi to weight divided by (height multiplied by height).
Display "Weight: " plus weight plus " kg".
Display "Height: " plus height plus " m".
Display "BMI: " plus round(bmi, 1).
If bmi is less than 18.5:
Display "Category: Underweight".
Otherwise if bmi is less than 25:
Display "Category: Normal".
Otherwise if bmi is less than 30:
Display "Category: Overweight".
Otherwise:
Display "Category: Obese".
End if.
Output:
Weight: 70 kg
Height: 1.75 m
BMI: 22.9
Category: Normal
2.2 Type Conversion
Definition: Type conversion is the process of changing a value from one data type to another, such as converting text to a number or a number to text.
Explanation: It is commonly used when performing operations that require compatible data types, especially when user input (which is always text) needs to be used in calculations.
Why Convert Types?
Definition: Type conversion is necessary because user input is always received as text, and arithmetic operations require numeric values.
In UNEL, every value has a type: integer, decimal, text, boolean, list, or nothing. Sometimes you need to change a value from one type to another.
The Convert Statement
Definition: The Convert statement changes a value from one data type to another using natural English syntax like 'Convert name to a number.'
The most common conversion โ user input (always text) to a number:
Ask "Enter a number: " and store in response.
Note: At this point, response is TEXT, like "42".
Convert response to a number.
Note: Now response is the INTEGER 42.
Display response plus 10. Note: Shows 52, not "4210".
Conversion Functions
Definition: Conversion functions like to_number(), to_text(), and to_decimal() provide explicit type conversion between UNEL's data types.
| Function | Purpose | Example | Result |
|---|---|---|---|
to_integer(x) |
Convert to integer | to_integer("42") |
42 |
to_decimal(x) |
Convert to decimal | to_decimal("3.14") |
3.14 |
to_text(x) |
Convert to text | to_text(42) |
"42" |
to_boolean(x) |
Convert to boolean | to_boolean(1) |
true |
typeof(x) |
Check the type | typeof(42) |
"integer" |
Examples
Definition: Examples demonstrate practical applications of the concepts being taught, showing complete runnable programs with expected output.
Note: Number to Text.
Set score to 95.
Set message to "Your score is " plus to_text(score) plus " out of 100.".
Display message.
Note: Text to Integer.
Set text_number to "42".
Set actual_number to to_integer(text_number).
Display actual_number plus 8.
Note: Text to Decimal.
Set text_decimal to "3.14".
Set pi_value to to_decimal(text_decimal).
Display pi_value multiplied by 2.
Note: Check the type of a value.
Display typeof(42).
Display typeof(3.14).
Display typeof("Hello").
Display typeof(true).
Display typeof([1, 2, 3]).
Display typeof(nothing).
Output:
Your score is 95 out of 100.
50
6.28
integer
decimal
text
boolean
list
nothing
2.3 Mixed Data Types
Definition: Mixed data types refer to the use of different types of values (such as numbers, text, and booleans) together within expressions or operations.
Explanation: UNEL allows certain combinations, such as joining numbers with text (automatic conversion), but requires explicit conversion when performing arithmetic with text values.
Combining Numbers and Text
Definition: Combining numbers and text uses the plus operator to join numeric values with string values, with automatic conversion to text.
When you use plus with a number and text, UNEL automatically converts the number to text:
Set name to "Alice".
Set age to 25.
Display name plus " is " plus age plus " years old.".
Output: Alice is 25 years old.
This works because UNEL converts 25 to "25" when joining with text.
Arithmetic with Mixed Numbers
Definition: Arithmetic with mixed numbers shows how integers and decimals can be used together in calculations, with UNEL automatically handling type promotion.
When you mix integers and decimals in arithmetic, the result is a decimal:
Set whole to 7.
Set fraction to 2.5.
Set result to whole plus fraction.
Display result. Note: 9.5
Display typeof(result). Note: decimal
Output:
9.5
decimal
When Mixing Fails
Definition: Mixing fails when attempting arithmetic operations on text values that have not been explicitly converted to numbers, producing a type error.
You cannot do arithmetic with text that looks like a number โ you must convert first:
Note: This will FAIL:
Note: Set result to "10" plus 5. โ This concatenates: "105"
Note: This is CORRECT:
Set message to "10".
Convert message to a number.
Set result to message plus 5.
Display result. Note: 15
Output:
15
2.4 Floating-Point Errors
Definition: Floating-point errors are small inaccuracies that occur when performing calculations with decimal numbers due to how they are represented in binary form inside a computer.
Explanation: Some decimal values (like 0.1 or 0.2) cannot be represented exactly in binary, which can lead to slight rounding errors in results. These errors are usually very small but can affect precision in calculations.
Why 0.1 + 0.2 โ 0.3
Definition: The inequality 0.1 + 0.2 โ 0.3 occurs because some decimal values cannot be represented exactly in binary, causing tiny rounding errors.
Computers store decimal numbers in binary, which can cause tiny rounding errors:
Set first_value to 0.1.
Set second_value to 0.2.
Set result to first_value plus second_value.
Display result. Note: May show 0.30000000000000004
Output:
0.30000000000000004
How to Handle This
Definition: Floating-point errors are handled using the round() function to control decimal precision and eliminate tiny rounding artifacts.
Use the round() function to control precision:
Set first_value to 0.1.
Set second_value to 0.2.
Set result to round(first_value plus second_value, 2).
Display result. Note: 0.3
Output:
0.3
Practical Example โ Money Calculations
Definition: Money calculations demonstrate proper use of rounding functions to ensure financial computations produce accurate, human-readable results.
Set price to 19.99.
Set tax_rate to 0.18.
Set tax to round(price multiplied by tax_rate, 2).
Set total to round(price plus tax, 2).
Display "Price: โน" plus price.
Display "Tax: โน" plus tax.
Display "Total: โน" plus total.
Output:
Price: โน19.99
Tax: โน3.6
Total: โน23.59
2.5 Dividing Integers
Definition: Dividing integers in UNEL always produces a decimal result, even when both operands are whole numbers.
Explanation: This ensures precision in calculations. If only the whole part is needed, functions like floor() can be used, and mod() can be used to obtain the remainder.
Division Always Returns a Decimal
Definition: Division in UNEL always returns a decimal result, even when both operands are whole numbers, ensuring precision in calculations.
In UNEL, dividing two integers returns a decimal result:
Set first_number to 7.
Set second_number to 2.
Display first_number plus " divided by " plus second_number plus " = " plus (first_number divided by second_number).
Output: 7 divided by 2 = 3.5
Floor Division โ Getting Only the Whole Part
Definition: Floor division uses the floor() function to get only the whole number portion of a division result, discarding the decimal part.
Use floor() to get the integer portion:
Set first_number to 7.
Set second_number to 2.
Set whole_part to floor(first_number divided by second_number).
Set remainder to mod(first_number, second_number).
Display "7 รท 2 = " plus whole_part plus " remainder " plus remainder.
Output: 7 รท 2 = 3 remainder 1
The Modulo Operation
Definition: The modulo operation uses mod() to return the remainder after division, useful for checking divisibility and cycling through values.
mod(a, b) returns the remainder after division:
Note: Check if a number is even or odd.
Set chosen_number to 17.
If mod(chosen_number, 2) is equal to 0:
Display chosen_number plus " is even.".
Otherwise:
Display chosen_number plus " is odd.".
End if.
Output: 17 is odd.
2.6 The Math Module
Definition: The Math module is a built-in module that provides advanced mathematical functions and constants for performing calculations in UNEL.
Explanation: It includes functions for trigonometry, powers, roots, and constants like ฯ (PI) and e. The module must be imported before use.
Built-in Math Functions
Definition: Built-in math functions include abs(), round(), max(), min(), power(), and sqrt() โ available without importing any module.
UNEL provides many math functions that you can use without importing anything:
Display "โโโ Basic Math Functions โโโ".
Display "abs(-7): " plus abs(-7).
Display "sqrt(144): " plus sqrt(144).
Display "power(2, 10): " plus power(2, 10).
Display "round(3.14159, 2): " plus round(3.14159, 2).
Display "floor(3.9): " plus floor(3.9).
Display "ceil(3.1): " plus ceil(3.1).
Display "mod(17, 5): " plus mod(17, 5).
Display "min(3, 7): " plus min(3, 7).
Display "max(3, 7): " plus max(3, 7).
Output:
โโโ Basic Math Functions โโโ
abs(-7): 7
sqrt(144): 12.0
power(2, 10): 1024
round(3.14159, 2): 3.14
floor(3.9): 3
ceil(3.1): 4
mod(17, 5): 2
min(3, 7): 3
max(3, 7): 7
The Math Module (Import for Advanced Functions)
Definition: The Math module provides advanced mathematical functions and constants like PI, e, trigonometry, and logarithms after being imported.
Import Math.
Display "โโโ Math Module โโโ".
Display "Math.PI: " plus Math.PI.
Display "Math.E: " plus Math.E.
Display "Math.sqrt(16): " plus Math.sqrt(16).
Display "Math.sin(0): " plus Math.sin(0).
Display "Math.cos(0): " plus Math.cos(0).
Display "Math.tan(0): " plus Math.tan(0).
Display "Math.floor(3.7): " plus Math.floor(3.7).
Display "Math.ceil(3.2): " plus Math.ceil(3.2).
Display "power(2, 8): " plus power(2, 8).
Output:
โโโ Math Module โโโ
Math.PI: 3.141592653589793
Math.E: 2.718281828459045
Math.sqrt(16): 4.0
Math.sin(0): 0.0
Math.cos(0): 1.0
Math.tan(0): 0.0
Math.floor(3.7): 3
Math.ceil(3.2): 4
power(2, 8): 256
Additional Math Functions
Definition: Additional math functions include logarithms, trigonometric functions, and ceiling/floor operations for specialized mathematical computations.
| Function | Description | Example | Result |
|---|---|---|---|
factorial(n) |
n! | factorial(5) |
120 |
gcd(a, b) |
Greatest common divisor | gcd(12, 8) |
4 |
lcm(a, b) |
Least common multiple | lcm(4, 6) |
12 |
is_prime(n) |
Check if prime | is_prime(17) |
true |
sign(x) |
Sign of number | sign(-5) |
-1 |
clamp(x, lo, hi) |
Restrict to range | clamp(15, 0, 10) |
10 |
digits(n) |
List of digits | digits(123) |
[1, 2, 3] |
digit_sum(n) |
Sum of digits | digit_sum(123) |
6 |
Practical Program: EMI Calculator
Definition: The EMI calculator demonstrates a real-world application combining variables, math functions, and formatted output to compute loan payments.
Note: Equated Monthly Installment Calculator.
Set principal to 100000.
Set annual_rate to 8.5.
Set months to 12.
Note: Monthly interest rate.
Set monthly_rate to annual_rate divided by 12 divided by 100.
Note: EMI Formula: P ร r ร (1+r)^n / ((1+r)^n - 1).
Set factor to power(1 plus monthly_rate, months).
Set emi to principal multiplied by monthly_rate multiplied by factor divided by (factor minus 1).
Set total to round(emi multiplied by months, 2).
Display "Loan: โน" plus principal.
Display "Rate: " plus annual_rate plus "% per annum".
Display "Tenure: " plus months plus " months".
Display "Monthly EMI: โน" plus round(emi, 2).
Display "Total Payment: โน" plus total.
Display "Interest Paid: โน" plus round(total minus principal, 2).
Output:
Loan: โน100000
Rate: 8.5% per annum
Tenure: 12 months
Monthly EMI: โน8729.93
Total Payment: โน104759.16
Interest Paid: โน4759.16
2.7 Formatting Code
Definition: Formatting code is the practice of organizing and structuring program code to improve readability, clarity, and maintainability.
Explanation: It includes using proper indentation, meaningful variable names, spacing, and comments to make the code easy to understand and follow.
Best Practices for Readable Code
Definition: Best practices for readable code include using descriptive variable names, consistent indentation, comments, and grouping related statements.
1. Use meaningful variable names:
Note: BAD โ What does marks represent?
Set marks to 75.
Note: GOOD โ The name explains the purpose.
Set student_marks to 75.
2. Use comments to organize sections:
Note: โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Note: Student Grade Calculator
Note: โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Note: โโโ Input โโโ
Set marks to 85.
Note: โโโ Processing โโโ
Set grade to "B".
If marks is greater than or equal to 90:
Set grade to "A+".
Otherwise if marks is greater than or equal to 80:
Set grade to "A".
End if.
Note: โโโ Output โโโ
Display "Marks: " plus marks plus " โ Grade: " plus grade.
Output:
Marks: 85 โ Grade: A
3. Indent blocks consistently:
Note: GOOD โ clear indentation shows structure.
Set temperature to 50.
If temperature is greater than 0:
If temperature is greater than 100:
Display "Very large".
Otherwise:
Display "Moderate".
End if.
Otherwise:
Display "Negative".
End if.
Output:
Very large
Moderate
Negative
4. Group related statements:
Note: User details.
Set name to "Alice".
Set age to 25.
Set city to "Mumbai".
Note: Course details.
Set course to "Computer Science".
Set semester to 6.
Set gpa to 3.8.
2.8 Chapter Summary
Definition: The chapter summary consolidates expression concepts including type conversion, mixed types, floating-point handling, math functions, and code formatting.
| Concept | Syntax | Example |
|---|---|---|
| Convert to number | Convert x to a number. |
Convert age to a number. |
| Convert function | to_integer(x) |
to_integer("42") โ 42 |
| Check type | typeof(x) |
typeof(3.14) โ "decimal" |
| Floor division | floor(a divided by b) |
floor(7 / 2) โ 3 |
| Remainder | mod(a, b) |
mod(17, 5) โ 2 |
| Rounding | round(x, places) |
round(3.14159, 2) โ 3.14 |
| Square root | sqrt(x) |
sqrt(25) โ 5.0 |
| Power | power(x, y) |
power(2, 10) โ 1024 |
| Import module | Import Math. |
Import Math. |
๐ Try It Yourself โ Interactive Programs
Definition: Interactive programs are input-based exercises using the Ask statement that allow learners to practice building dynamic, user-driven applications.
Program 1: Unit converter (input-based).
Note: Kilometers to Miles Converter.
Ask "Enter distance in kilometers: " and store in km.
Convert km to a number.
Set miles to km multiplied by 0.621371.
Display km plus " km = " plus round(miles, 2) plus " miles.".
Sample Run:
Enter distance in kilometers: 42
42 km = 26.1 miles.
Program 2: Percentage calculator (input-based).
Ask "Enter total marks: " and store in total.
Ask "Enter marks obtained: " and store in obtained.
Convert total to a number.
Convert obtained to a number.
Set percentage to round((obtained divided by total) multiplied by 100, 2).
Display "Percentage: " plus percentage plus "%".
Sample Run:
Enter total marks: 500
Enter marks obtained: 435
Percentage: 87.0%
Program 3: Simple interest calculator (input-based).
Ask "Enter principal amount: " and store in principal.
Ask "Enter rate of interest (%): " and store in rate.
Ask "Enter time (years): " and store in time.
Convert principal to a number.
Convert rate to a number.
Convert time to a number.
Set interest to (principal multiplied by rate multiplied by time) divided by 100.
Set total to principal plus interest.
Display "Principal: โน" plus principal.
Display "Rate: " plus rate plus "%".
Display "Time: " plus time plus " years".
Display "Interest: โน" plus interest.
Display "Total: โน" plus total.
Sample Run:
Enter principal amount: 50000
Enter rate of interest (%): 8
Enter time (years): 3
Principal: โน50000
Rate: 8%
Time: 3 years
Interest: โน12000
Total: โน62000
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Chapter 3: Objects
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Definition: An object is a value that contains both data and associated operations, allowing it to be manipulated through its properties and functions.
Explanation: In UNEL, many data types such as strings, lists, and dictionaries are treated as objects. This means they not only store values but also provide built-in operations that can be performed on them, making programming more structured and expressive.
3.1 Strings Revisited
Definition: A string is an object representing a sequence of characters that supports various built-in operations and properties.
Explanation: In UNEL, strings are not just plain text but objects that provide functions for manipulation, such as accessing characters, changing case, trimming whitespace, and transforming content, making text processing flexible and powerful.
Strings as Objects
Definition: In UNEL, strings are objects that not only store text but also provide built-in functions for manipulation such as length calculation, case conversion, and searching.
In UNEL, a string is not just text โ it is an object with properties and operations. Let us explore strings in depth.
String Length
Definition: The length() function returns the number of characters in a string, counting all letters, spaces, and symbols.
Set message to "Hello, UNEL!".
Display "Text: " plus message.
Display "Length: " plus length(message). Note: 12
Output:
Text: Hello, UNEL!
Length: 12
Accessing Individual Characters
Definition: Individual characters in a string are accessed using 1-based indexing with square brackets, where position 1 is the first character.
Use char_at(string, position) with 1-based indexing:
Set word to "UNEL".
Display "Character 1: " plus char_at(word, 1). Note: U
Display "Character 2: " plus char_at(word, 2). Note: N
Display "Character 3: " plus char_at(word, 3). Note: E
Display "Character 4: " plus char_at(word, 4). Note: L
Output:
U
N
E
L
Case Operations
Definition: Case operations transform the letter casing of strings using functions like uppercase(), lowercase(), and capitalize().
Set message to "Hello, World!".
Display uppercase(message). Note: HELLO, WORLD!
Display lowercase(message). Note: hello, world!
Display capitalize("hello"). Note: Hello
Output:
HELLO, WORLD!
hello, world!
Hello
Checking String Properties
Definition: String property checks like is_upper(), is_lower(), and is_digit() test whether a string meets specific character conditions, returning a boolean.
Display is_upper("HELLO"). Note: true
Display is_upper("Hello"). Note: false
Display is_lower("hello"). Note: true
Display is_lower("Hello"). Note: false
Output:
true
false
true
false
Trimming Whitespace
Definition: The trim() function removes leading and trailing whitespace from a string, cleaning up user input and formatted text.
Set messy to " Hello, World! ".
Display "'" plus trim(messy) plus "'". Note: 'Hello, World!'
Display "'" plus trim_left(messy) plus "'". Note: 'Hello, World! '
Display "'" plus trim_right(messy) plus "'". Note: ' Hello, World!'
Output:
'Hello, World!'
'Hello, World! '
' Hello, World!'
Reversing a String
Definition: The reverse() function returns a new string with the characters in reversed order, useful for palindrome checks and text transformations.
Set word to "UNEL".
Display "Reversed: " plus reverse(word). Note: LENU
Output:
Reversed: LENU
3.2 Formatted Strings
Definition: Formatted strings are strings that allow embedding of variables or expressions directly within the text using placeholders.
Explanation: In UNEL, formatted strings use curly braces {} to insert values into a string, making it easier to construct dynamic and readable output without manually concatenating multiple parts.
String Interpolation
Definition: String interpolation in depth shows advanced usage of curly braces {} to embed complex expressions and multiple variables within formatted strings.
Embed expressions inside strings using curly braces:
Set name to "Alice".
Set marks to 95.
Set subject to "Mathematics".
Display "{name} scored {marks} in {subject}.".
Output: Alice scored 95 in Mathematics.
Building Complex Strings
Definition: Building complex strings combines interpolation, concatenation, and formatting functions to construct detailed, dynamic text output.
Set product to "Laptop".
Set price to 49999.
Set discount to 10.
Set final_price to price minus (price multiplied by discount divided by 100).
Display "Product: {product}".
Display "Original Price: โน{price}".
Display "Discount: {discount}%".
Display "Final Price: โน{final_price}".
Output:
Product: Laptop
Original Price: โน49999
Discount: 10%
Final Price: โน44999.1
Padding and Alignment
Definition: Padding functions (pad_left, pad_right, center) add characters to align text within a specified width for formatted output.
Note: Right-align numbers in a table.
Set items to ["Apple", "Banana", "Cherry"].
Set prices to [50, 30, 80].
Display "โโ Price List โโโโโโโโโโโโโโ".
Repeat from 1 to length(items) as i:
Set name_col to pad_right(items[i], 12, " ").
Set price_col to pad_left(to_text(prices[i]), 5, " ").
Display " " plus name_col plus "โน" plus price_col.
End repeat.
Output:
โโ Price List โโโโโโโโโโโโโโ
Apple โน 50
Banana โน 30
Cherry โน 80
Repeating Strings
Definition: The repeat_string() function duplicates a string a specified number of times, useful for creating separators, patterns, and visual elements.
Display repeat_string("โ", 30). Note: โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Display repeat_string("โ
", 5). Note: โ
โ
โ
โ
โ
Output:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โ
โ
โ
โ
3.3 Variables Revisited
Definition: Variables are references to values in memory, meaning they point to data rather than containing the data itself.
Explanation: In UNEL, assigning one variable to another creates a reference to the same value, especially for complex types like lists. Changes made through one reference may affect the original value unless an explicit copy is created.
Variables Hold References
Definition: Variables in UNEL hold references to values in memory, meaning assigning one variable to another creates a link to the same data.
When you assign a list to two variables, both point to the same list:
Set original to [1, 2, 3].
Set copy_ref to original.
Add 4 to copy_ref.
Display "Original: " plus original. Note: [1, 2, 3, 4] โ changed!
Display "Copy: " plus copy_ref. Note: [1, 2, 3, 4]
Output:
[1, 2, 3, 4] โ changed!
[1, 2, 3, 4]
Deep Copying
Definition: Deep copying creates an independent duplicate of a value using copy(), ensuring changes to the copy do not affect the original.
To create an independent copy, use deep_copy():
Set original to [1, 2, 3].
Set independent to deep_copy(original).
Add 4 to independent.
Display "Original: " plus original. Note: [1, 2, 3] โ unchanged
Display "Independent: " plus independent. Note: [1, 2, 3, 4]
Output:
[1, 2, 3] โ unchanged
[1, 2, 3, 4]
The Nothing Value
Definition: Nothing is UNEL's null value representing the absence of a value, used for uninitialized variables and empty returns.
nothing represents the absence of a value:
Set result to nothing.
Display "Result: " plus result. Note: Result: nothing
Display "Is nothing: " plus (result is equal to nothing). Note: true
Output:
Result: nothing
true
Multiple Assignment
Definition: Multiple assignment allows setting several variables on separate lines to build up related data before processing them together.
Assign multiple variables in one line:
Set width to 1.
Set height to 2.
Set depth to 3.
Display "x=" plus width plus ", y=" plus height plus ", z=" plus depth.
Output:
x=1, y=2, z=3
3.4 List Basics
Definition: A list is an ordered, mutable collection of values that can store multiple items in a single variable.
Explanation: Lists in UNEL can contain elements of any data type and allow operations such as accessing, adding, removing, and modifying items. They use 1-based indexing, where the first element is at position 1, making them intuitive and easy to work with.
What is a List?
Definition: A list is an ordered, mutable collection of values enclosed in square brackets that can store items of any data type.
A list is an ordered collection of values. Lists can hold any type and any number of items.
Set empty_collection to [].
Set numbers to [10, 20, 30, 40, 50].
Set names to ["Alice", "Bob", "Charlie"].
Set mixed to [1, "hello", true, 3.14].
Display "Numbers: " plus numbers.
Display "Names: " plus names.
Display "Mixed: " plus mixed.
Output:
Numbers: [10, 20, 30, 40, 50]
Names: [Alice, Bob, Charlie]
Mixed: [1, hello, true, 3.14]
1-Based Indexing
Definition: UNEL uses 1-based indexing where the first element of a list is at position 1, making lists intuitive and aligned with natural counting.
UNEL uses 1-based indexing โ the first element is at position 1 (not 0):
Set fruits to ["Apple", "Banana", "Cherry", "Date"].
Display "First: " plus fruits[1]. Note: Apple
Display "Second: " plus fruits[2]. Note: Banana
Display "Third: " plus fruits[3]. Note: Cherry
Display "Fourth: " plus fruits[4]. Note: Date
Display "Length: " plus length(fruits). Note: 4
Output:
Apple
Banana
Cherry
Date
4
Modifying Lists
Definition: Lists are modified by adding items with Add, removing items with Remove, and updating elements by assigning to a specific index.
Set colors to ["Red", "Green", "Blue"].
Display "Original: " plus colors.
Note: Add an item.
Add "Yellow" to colors.
Display "Added Yellow: " plus colors.
Note: Change an item.
Set colors[2] to "Purple".
Display "Changed Green to Purple: " plus colors.
Note: Remove an item.
Remove item 3 from colors.
Display "Removed Blue: " plus colors.
Output:
Original: [Red, Green, Blue]
Added Yellow: [Red, Green, Blue, Yellow]
Changed Green to Purple: [Red, Purple, Blue, Yellow]
Removed Blue: [Red, Purple, Yellow]
Iterating Over Lists
Definition: Iterating over lists uses the For each loop to access and process every element in the collection one by one.
Set scores to [85, 92, 78, 95, 88].
Set total to 0.
For each score in scores:
Set total to total plus score.
End for.
Set average to total divided by length(scores).
Display "Average score: " plus average.
Output:
Average score: 87.6
3.5 Tuple Basics
Definition: A tuple is an ordered collection of values that is immutable, meaning its elements cannot be changed after creation.
Explanation: Tuples are used to store fixed data such as coordinates or constant groups of values. Unlike lists, they do not allow modification, which ensures data integrity and consistency.
What is a Tuple?
Definition: A tuple is an ordered, immutable collection of values enclosed in parentheses that cannot be changed after creation.
A tuple is like a list, but immutable โ once created, it cannot be changed. Use tuples for fixed collections like coordinates, RGB colors, or dates.
Set point to tuple(10, 20).
Set color to tuple(255, 128, 0).
Display "Point: " plus point.
Display "Color: " plus color.
Display "Is tuple: " plus is_tuple(point). Note: true
Output:
Point: (10, 20)
Color: (255, 128, 0)
Is tuple: true
Unpacking Tuples
Definition: Unpacking tuples extracts each element into separate variables in a single statement, providing a clean way to access grouped data.
Set coordinates to [42, 17].
Display "X: " plus coordinates[1].
Display "Y: " plus coordinates[2].
Output:
42
17
Tuples vs Lists
Definition: Tuples are immutable and used for fixed data, while lists are mutable and used for collections that need to change โ choosing between them depends on whether the data should be modifiable.
| Feature | List | Tuple |
|---|---|---|
| Mutable | Yes โ can add, remove, change | No โ fixed once created |
| Syntax | [1, 2, 3] |
tuple(1, 2, 3) |
| Use case | Collections that change | Fixed data like coordinates |
3.6 Chapter Summary
Definition: The chapter summary consolidates object concepts including string operations, formatted strings, variable references, lists, and tuples.
| Concept | Syntax | Example |
|---|---|---|
| String length | length(text) |
length("Hello") โ 5 |
| Character at index | char_at(text, pos) |
char_at("ABC", 2) โ "B" |
| Uppercase | uppercase(text) |
uppercase("hi") โ "HI" |
| Lowercase | lowercase(text) |
lowercase("HI") โ "hi" |
| String interpolation | "text {var} text" |
"{name} is {age}" |
| Create list | [item1, item2, ...] |
Set x to [1, 2, 3]. |
| List access | list[index] |
x[1] โ first element |
| Add to list | Add item to list. |
Add "d" to letters. |
| Create tuple | tuple(a, b, c) |
tuple(10, 20) |
| Deep copy | deep_copy(value) |
deep_copy(my_list) |
๐ Try It Yourself โ Interactive Programs
Definition: Interactive programs are input-based exercises using the Ask statement that allow learners to practice building dynamic, user-driven applications.
Program 1: Shopping list builder (input-based).
Set shopping_list to [].
Ask "How many items to add? " and store in count.
Convert count to a number.
Repeat from 1 to count as i:
Ask "Enter item: " and store in item_name.
Add item_name to shopping_list.
End repeat.
Display "".
Display "โโโ Your Shopping List โโโ".
Repeat from 1 to length(shopping_list) as i:
Display " " plus i plus ". " plus shopping_list[i].
End repeat.
Display "Total items: " plus length(shopping_list).
Sample Run:
How many items to add? 3
Enter item 1: Milk
Enter item 2: Bread
Enter item 3: Eggs
โโโ Your Shopping List โโโ
1. Milk
2. Bread
3. Eggs
Total items: 3
Program 2: String analyzer (input-based).
Ask "Enter a word or sentence: " and store in message.
Display "".
Display "โโโ String Analysis โโโ".
Display "Text: '" plus message plus "'".
Display "Length: " plus length(message) plus " characters".
Display "Uppercase: " plus uppercase(message).
Display "Lowercase: " plus lowercase(message).
Display "Reversed: " plus reverse(message).
Display "Word count: " plus word_count(message).
Sample Run:
Enter a word or sentence: Hello World
โโโ String Analysis โโโ
Text: 'Hello World'
Length: 11 characters
Uppercase: HELLO WORLD
Lowercase: hello world
Reversed: dlroW olleH
Word count: 2
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Chapter 4: Decisional / Conditional Statements
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Definition: Decisional or conditional statements are control structures that allow a program to execute different blocks of code based on whether a condition evaluates to true or false.
Explanation: In UNEL, these statements use boolean expressions to guide the flow of execution. Constructs such as If, Otherwise, and Unless enable programs to make decisions, handle different scenarios, and respond dynamically to input or conditions.
4.1 Boolean Values
Definition: Boolean values are a data type that represents one of two possible states: true or false.
Explanation: In UNEL, booleans are used to control decision-making and logical operations. They are commonly produced by comparisons and conditions, and can also be expressed using yes and no for readability.
What is a Boolean?
Definition: A boolean is a data type with exactly two possible values โ true or false โ used to represent logical conditions and control program flow.
A boolean is a value that is either true or false. Booleans are the foundation of all decision-making in programming.
Set is_raining to true.
Set has_umbrella to false.
Display "Is it raining? " plus is_raining. Note: true
Display "Have umbrella? " plus has_umbrella. Note: false
Output:
true
false
UNEL also accepts yes and no as boolean values:
Set is_student to yes.
Set is_graduated to no.
Comparison Operators โ Producing Booleans
Definition: Comparison operators evaluate relationships between values and produce boolean results using natural English phrases like 'is equal to' and 'is greater than.'
Every comparison evaluates to a boolean:
Set width to 10.
Set height to 20.
Display width plus " is equal to " plus height plus ": " plus (width is equal to height). Note: false
Display width plus " is not equal to " plus height plus ": " plus (width is not equal to height). Note: true
Display width plus " is greater than " plus height plus ": " plus (width is greater than height). Note: false
Display width plus " is less than " plus height plus ": " plus (width is less than height). Note: true
Display width plus " is greater than or equal to 10: " plus (width is greater than or equal to 10). Note: true
Display width plus " is less than or equal to 5: " plus (width is less than or equal to 5). Note: false
Output:
false
true
false
true
true
false
| English Expression | Symbol | Meaning |
|---|---|---|
is equal to |
= |
Equal |
is not equal to |
!= |
Not equal |
is greater than |
> |
Greater |
is less than |
< |
Less |
is greater than or equal to |
>= |
Greater or equal |
is less than or equal to |
<= |
Less or equal |
4.2 If-Else Statements
Definition: If-Else statements are conditional constructs that execute one block of code when a condition is true and an alternative block when the condition is false.
Explanation: In UNEL, the If statement evaluates a boolean expression, and based on the result, either the main block or the Otherwise block is executed. This allows programs to make decisions and handle different situations dynamically.
Basic If Statement
Definition: The basic If statement executes a block of code only when a specified condition evaluates to true, providing single-branch decision making.
Set temperature to 35.
If temperature is greater than 30:
Display "It's a hot day! Stay hydrated.".
End if.
Output:
It's a hot day! Stay hydrated.
The body only executes if the condition is true.
If-Otherwise (If-Else)
Definition: The If-Otherwise construct provides two-branch decision making, executing one block when a condition is true and an alternative block when it is false.
Set age to 17.
If age is greater than or equal to 18:
Display "You are eligible to vote.".
Otherwise:
Display "You are not yet eligible to vote.".
End if.
Output:
You are eligible to vote.
You are not yet eligible to vote.
If-Otherwise If-Otherwise (Chained Conditions)
Definition: The If-Otherwise construct provides two-branch decision making, executing one block when a condition is true and an alternative block when it is false.
Set marks to 78.
If marks is greater than or equal to 90:
Display "Grade: A+ (Outstanding)".
Otherwise if marks is greater than or equal to 80:
Display "Grade: A (Excellent)".
Otherwise if marks is greater than or equal to 70:
Display "Grade: B (Very Good)".
Otherwise if marks is greater than or equal to 60:
Display "Grade: C (Good)".
Otherwise if marks is greater than or equal to 50:
Display "Grade: D (Average)".
Otherwise:
Display "Grade: F (Fail)".
End if.
Output:
Grade: A+ (Outstanding)
Grade: A (Excellent)
Grade: B (Very Good)
Grade: C (Good)
Grade: D (Average)
Grade: F (Fail)
The Unless Statement (Inverted If)
Definition: The Unless statement is an inverted If that executes its block only when the condition is false, providing a more natural way to express negative conditions.
Unless runs the body when the condition is FALSE:
Set logged_in to false.
Unless logged_in:
Display "Please log in to continue.".
End unless.
Output:
Please log in to continue.
This is equivalent to If not logged_in:.
4.3 Boolean Operations
Definition: Boolean operations are logical operations that combine or modify boolean values to produce a true or false result.
Explanation: In UNEL, operators such as and, or, and not are used to form complex conditions. These operations help control program flow by evaluating multiple conditions or reversing logical outcomes.
AND โ Both Must Be True
Definition: The AND operator combines two conditions and returns true only when both conditions are true, requiring all parts to be satisfied.
Set age to 25.
Set has_license to true.
If age is greater than or equal to 18 and has_license:
Display "You can drive.".
Otherwise:
Display "You cannot drive.".
End if.
Output:
You can drive.
You cannot drive.
OR โ At Least One Must Be True
Definition: The OR operator combines two conditions and returns true when at least one condition is true, requiring only one part to be satisfied.
Set day to "Saturday".
If day is equal to "Saturday" or day is equal to "Sunday":
Display "It's the weekend!".
Otherwise:
Display "It's a weekday.".
End if.
Output:
It's the weekend!
It's a weekday.
NOT โ Reverses the Condition
Definition: The NOT operator inverts a boolean value, turning true to false and false to true, used to express the opposite of a condition.
Set is_raining to false.
If not is_raining:
Display "No need for an umbrella today.".
End if.
Output:
No need for an umbrella today.
Combining Operators
Definition: Combining boolean operators allows building complex logical expressions by chaining AND, OR, and NOT with comparison operators.
Set age to 25.
Set income to 50000.
Set credit_score to 750.
If (age is greater than or equal to 21 and income is greater than 30000) or credit_score is greater than 700:
Display "Eligible for a credit card.".
Otherwise:
Display "Not eligible.".
End if.
Output:
Eligible for a credit card.
Not eligible.
4.4 Operator Precedence
Definition: Operator precedence is the set of rules that determines the order in which operators are evaluated in an expression.
Explanation: In UNEL, logical operators are evaluated in a specific order โ not first, followed by comparisons, then and, and finally or. Understanding precedence ensures that expressions are interpreted correctly, especially when multiple operators are used together.
When multiple operators appear, UNEL evaluates them in this order:
| Priority | Operator | Example |
|---|---|---|
| 1 (Highest) | not |
not true โ false |
| 2 | Comparisons (is greater than, etc.) |
5 is greater than 3 โ true |
| 3 | and |
true and false โ false |
| 4 (Lowest) | or |
true or false โ true |
Example
Definition: An example demonstrates a complete, runnable program that applies the concept being taught with realistic input and expected output.
Set is_sunny to true.
Set is_raining to false.
Set is_windy to true.
Note: Without parentheses:
Display is_sunny or is_raining and is_windy. Note: true (and evaluates before or)
Note: With parentheses:
Display (is_sunny or is_raining) and is_windy. Note: true
Output:
true (and evaluates before or)
true
4.5 Nested Statements
Definition: Nested statements are control structures placed inside other control structures, allowing multiple levels of decision-making within a program.
Explanation: In UNEL, statements like If or loops can be written inside other If or loop blocks. This enables handling of complex conditions and hierarchical logic by evaluating one condition within the context of another.
Nesting If Inside If
Definition: Nesting If statements places conditional blocks inside other conditional blocks, enabling multi-level decision trees for complex logic.
Set age to 25.
Set has_id to true.
Set has_ticket to true.
If age is greater than or equal to 18:
Display "Age verified.".
If has_id:
Display "ID verified.".
If has_ticket:
Display "Welcome to the event!".
Otherwise:
Display "You need a ticket.".
End if.
Otherwise:
Display "Please show your ID.".
End if.
Otherwise:
Display "You must be 18 or older.".
End if.
Output:
Age verified.
ID verified.
Welcome to the event!
You need a ticket.
Please show your ID.
You must be 18 or older.
Check/Match Statements (Switch)
Definition: Check/Match statements provide a structured alternative to chained If-Otherwise blocks, matching a value against multiple cases for cleaner decision logic.
When you have many conditions on the same value, use Check:
Set grade to "B".
Check grade:
When "A":
Display "Excellent โ 90% and above.".
When "B":
Display "Very Good โ 80% to 89%.".
When "C":
Display "Good โ 70% to 79%.".
When "D":
Display "Average โ 60% to 69%.".
When "F":
Display "Fail โ below 60%.".
Default:
Display "Invalid grade entered.".
End check.
Output:
Excellent โ 90% and above.
Very Good โ 80% to 89%.
Good โ 70% to 79%.
Average โ 60% to 69%.
Fail โ below 60%.
Invalid grade entered.
4.6 Conditional Expressions (Ternary)
Definition: Conditional expressions are concise expressions that return a value based on a condition, allowing simple decisions to be written in a single line.
Explanation: In UNEL, a conditional expression evaluates a condition and selects one of two values depending on whether the condition is true or false, making code shorter and more readable for simple choices.
For simple choices, use inline conditional expressions:
Set age to 20.
Set status to "adult" if age is greater than or equal to 18 otherwise "minor".
Display "Status: " plus status. Note: Status: adult
Set score to 45.
Set result to "Pass" if score is greater than or equal to 50 otherwise "Fail".
Display "Result: " plus result. Note: Result: Fail
Output:
Status: adult
Result: Fail
Practical Program: Ticket Pricing System
Definition: The ticket pricing system demonstrates real-world conditional logic using age-based pricing with multiple categories and discount rules.
Note: Ticket pricing based on age.
Ask "Enter your age: " and store in age.
Convert age to a number.
Set price to 0.
Set category to "Unknown".
If age is less than or equal to 5:
Set price to 0.
Set category to "Free (Infant)".
Otherwise if age is less than or equal to 12:
Set price to 50.
Set category to "Child".
Otherwise if age is less than or equal to 60:
Set price to 100.
Set category to "Adult".
Otherwise:
Set price to 60.
Set category to "Senior Citizen".
End if.
Display "".
Display "Category: " plus category.
Display "Ticket Price: โน" plus price.
Sample Run:
Enter your age: 35
Category: Adult
Ticket Price: โน100
๐ Try It Yourself โ Interactive Programs
Definition: Interactive programs are input-based exercises using the Ask statement that allow learners to practice building dynamic, user-driven applications.
Program 1: Login validator (input-based).
Constant CORRECT_PASSWORD is "unel2026".
Ask "Enter username: " and store in username.
Ask "Enter password: " and store in password.
If password is equal to CORRECT_PASSWORD:
Display "".
Display "Welcome, " plus username plus "! Login successful.".
Otherwise:
Display "".
Display "Access denied. Incorrect password.".
End if.
Sample Run:
Enter username: Jayaram
Enter password: unel2026
Welcome, Jayaram! Login successful.
Program 2: Grading system (input-based).
Ask "Enter student name: " and store in name.
Ask "Enter marks (out of 100): " and store in marks.
Convert marks to a number.
Set grade to "F (Fail)".
If marks is greater than or equal to 90:
Set grade to "A+ (Outstanding)".
Otherwise if marks is greater than or equal to 80:
Set grade to "A (Excellent)".
Otherwise if marks is greater than or equal to 70:
Set grade to "B (Very Good)".
Otherwise if marks is greater than or equal to 60:
Set grade to "C (Good)".
Otherwise if marks is greater than or equal to 50:
Set grade to "D (Average)".
End if.
Display "".
Display "Student: " plus name.
Display "Marks: " plus marks.
Display "Grade: " plus grade.
If marks is greater than or equal to 50:
Display "Result: PASS โ
".
Otherwise:
Display "Result: FAIL โ".
End if.
Sample Run:
Enter student name: Alice
Enter marks (out of 100): 85
Student: Alice
Marks: 85
Grade: A (Excellent)
Result: PASS โ
Program 3: Number classifier (input-based).
Ask "Enter a number: " and store in num.
Convert num to a number.
Display "".
If num is greater than 0:
Display num plus " is positive.".
Otherwise if num is less than 0:
Display num plus " is negative.".
Otherwise:
Display num plus " is zero.".
End if.
If mod(num, 2) is equal to 0:
Display num plus " is even.".
Otherwise:
Display num plus " is odd.".
End if.
Sample Run:
Enter a number: -7
-7 is negative.
-7 is odd.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Chapter 5: Loops
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Definition: Loops are control structures that repeatedly execute a block of code as long as a specified condition is met or for a defined number of iterations.
Explanation: In UNEL, loops such as While, Repeat, and For allow programs to automate repetitive tasks, process collections of data, and control iteration flow efficiently.
5.1 While Loop
Definition: A while loop is a control structure that repeatedly executes a block of code as long as a specified condition remains true.
Explanation: In UNEL, the condition is checked before each iteration. If the condition evaluates to true, the loop continues; if it becomes false, the loop stops. It is commonly used when the number of iterations is not known in advance.
Basic While Loop
Definition: The basic While loop structure evaluates a condition before each iteration and continues executing its block as long as the condition remains true.
The While loop repeats as long as its condition is true:
Set count to 1.
While count is less than or equal to 5:
Display "Count: " plus count.
Increase count by 1.
End while.
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Countdown Example
Definition: The countdown example demonstrates a While loop that decreases a counter from a starting value to zero, printing each step.
Set countdown to 10.
While countdown is greater than 0:
Display countdown.
Decrease countdown by 1.
End while.
Display "Liftoff! ๐".
Output:
Liftoff! ๐
Sum Until a Condition
Definition: Summing until a condition uses a While loop to accumulate values until a threshold or stopping criterion is reached.
Note: Sum numbers until the total exceeds 100.
Set total to 0.
Set counter to 1.
While total is less than or equal to 100:
Set total to total plus counter.
Increase counter by 1.
End while.
Display "Sum: " plus total.
Display "Numbers added: " plus (counter minus 1).
Infinite Loop Protection
Definition: Infinite loop protection involves ensuring that every While loop's condition will eventually become false, preventing the program from running forever.
Always make sure your condition will eventually become false:
Note: GOOD โ counter increases, so the loop ends.
Set step to 0.
While step is less than 5:
Display step.
Increase step by 1.
End while.
Note: BAD โ counter never changes, loop runs forever!
Note: Set step to 0.
Note: While step is less than 5:
Note: Display step.
Note: End while.
5.2 For Loop
Definition: A for loop is a control structure used to iterate over a sequence or repeat a block of code a specified number of times.
Explanation: In UNEL, for loops can be used to iterate through collections like lists or to run a loop over a defined range. They provide a clear and structured way to process elements one by one or perform repeated actions.
Repeat N Times
Definition: The Repeat statement executes a block of code a specified number of times, providing a simple counted loop without needing a counter variable.
Repeat 5 times:
Display "Hello!".
End repeat.
Output:
Hello!
Repeat From-To (Counted Loop)
Definition: The Repeat From-To loop iterates through a range of numbers from a start value to an end value, assigning each number to a loop variable.
Repeat from 1 to 10 as i:
Display "i = " plus i.
End repeat.
Counting Backwards
Definition: Counting backwards uses Repeat with a reversed range to iterate from a higher number down to a lower number.
UNEL automatically detects the direction:
Display "Countdown:".
Repeat from 10 to 1 as i:
Display i.
End repeat.
Display "Go!".
Output:
Countdown:
Go!
For Each Loop (Iterate Over Collections)
Definition: The For Each loop iterates over every element in a collection such as a list or string, processing each item one by one.
Set fruits to ["Apple", "Banana", "Cherry", "Date"].
For each fruit in fruits:
Display "๐ " plus fruit.
End for.
For Each with Index
Definition: For Each with Index provides both the element and its position number during iteration, useful for numbered output and position-dependent logic.
Set students to ["Alice", "Bob", "Charlie"].
For each student at position index in students:
Display index plus ". " plus student.
End for.
Output:
1. Alice
2. Bob
3. Charlie
For Each Over Dictionaries
Definition: For Each over dictionaries iterates through key-value pairs, providing access to both the key name and its associated value in each iteration.
Set capitals to {"India": "New Delhi", "Japan": "Tokyo", "France": "Paris"}.
For each country, capital in capitals:
Display "The capital of " plus country plus " is " plus capital plus ".".
End for.
Multiplication Table
Definition: The multiplication table program uses a Repeat loop to generate all products of a number from 1 to 10 in a formatted layout.
Set table_number to 7.
Display "โโโ " plus table_number plus " Times Table โโโ".
Repeat from 1 to 10 as i:
Display " " plus table_number plus " ร " plus i plus " = " plus (table_number multiplied by i).
End repeat.
5.3 Nested Loops
Definition: Nested loops are loops placed inside other loops, allowing repeated execution of a loop within each iteration of another loop.
Explanation: In UNEL, an inner loop runs completely for every iteration of the outer loop. This structure is commonly used for working with multi-dimensional data, patterns, and combinations.
Pattern Printing
Definition: Pattern printing uses nested loops to create visual patterns of characters like stars, forming shapes such as triangles and pyramids.
Note: Right triangle of stars.
Repeat from 1 to 5 as row:
Set line to "".
Repeat from 1 to row as col:
Set line to line plus "โ
".
End repeat.
Display line.
End repeat.
Output:
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
Number Pattern
Definition: Number patterns use nested loops to display sequences of numbers arranged in geometric shapes like right triangles.
Repeat from 1 to 5 as i:
Set line to "".
Repeat from 1 to i as j:
Set line to line plus to_text(j) plus " ".
End repeat.
Display line.
End repeat.
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Multiplication Chart
Definition: A multiplication chart uses nested loops to generate a complete grid showing the products of numbers from 1 to N.
Display " 1 2 3 4 5".
Display " โโโโโฌโโโโฌโโโโฌโโโโฌโโโโ".
Repeat from 1 to 5 as i:
Set row to to_text(i) plus " โ".
Repeat from 1 to 5 as j:
Set product to i multiplied by j.
Set row to row plus pad_left(to_text(product), 3, " ") plus "โ".
End repeat.
Display row.
End repeat.
Output:
1 2 3 4 5
โโโโโฌโโโโฌโโโโฌโโโโฌโโโโ
5.4 Break and Continue
Definition: Break and Continue are control statements used to alter the normal flow of loops during execution.
Explanation: In UNEL, Break immediately terminates the loop and exits it, while Continue skips the current iteration and moves to the next one. These statements provide finer control over loop behavior.
Break โ Exit the Loop Early
Definition: The Break statement immediately terminates the innermost loop, transferring execution to the first statement after the loop.
Note: Find the first number divisible by 7.
Repeat from 50 to 100 as i:
If mod(i, 7) is equal to 0:
Display "First number divisible by 7: " plus i.
Break.
End if.
End repeat.
Output: First number divisible by 7: 56
Continue โ Skip to the Next Iteration
Definition: The Continue statement skips the remaining code in the current loop iteration and jumps to the next iteration.
Note: Display only odd numbers.
Repeat from 1 to 10 as i:
If mod(i, 2) is equal to 0:
Continue.
End if.
Display i.
End repeat.
Output: 1 3 5 7 9
Practical Example: Input Validation Loop
Definition: Input validation loops use While with Break to repeatedly prompt users until they provide valid input meeting specified criteria.
Set valid to false.
While not valid:
Ask "Enter a positive number: " and store in response.
Convert response to a number.
If response is greater than 0:
Set valid to true.
Display "You entered: " plus response.
Otherwise:
Display "Invalid! Please enter a positive number.".
End if.
End while.
5.5 Loop Else
Definition: Loop Else is a construct that executes an additional block of code after a loop finishes, typically when no iterations occur or when the loop completes without interruption.
Explanation: In UNEL, the Else block is associated with loops like For and runs when the loop has no elements to iterate over or completes normally, providing a way to handle empty or fully processed cases.
For-Else Loop
Definition: The For-Else construct runs an Else block after a For loop completes normally, typically used to handle the case when no elements matched a search.
The Else block runs when the collection is empty:
Set empty_collection to [].
If length(empty_collection) is equal to 0:
Display "No items found.".
Otherwise:
For each element in empty_collection:
Display element.
End for.
End if.
Output: No items found.
Do-While Loop
Definition: The Do-While loop executes its block at least once before checking the condition, ensuring the body runs even if the condition starts as false.
Runs the body at least once, then checks the condition:
Set attempts to 0.
Do:
Increase attempts by 1.
Display "Attempt #" plus attempts.
While attempts is less than 3.
Display "Done after " plus attempts plus " attempts.".
Output:
Attempt #1
Attempt #2
Attempt #3
Done after 3 attempts.
๐ Try It Yourself โ Interactive Programs
Definition: Interactive programs are input-based exercises using the Ask statement that allow learners to practice building dynamic, user-driven applications.
Program 1: Multiplication table generator (input-based).
Ask "Enter a number for multiplication table: " and store in n.
Convert n to a number.
Display "".
Display "โโโ " plus n plus " Times Table โโโ".
Repeat from 1 to 10 as i:
Display " " plus n plus " ร " plus i plus " = " plus (n multiplied by i).
End repeat.
Sample Run:
Enter a number for multiplication table: 7
โโโ 7 Times Table โโโ
7 ร 1 = 7
7 ร 2 = 14
7 ร 3 = 21
7 ร 4 = 28
7 ร 5 = 35
7 ร 6 = 42
7 ร 7 = 49
7 ร 8 = 56
7 ร 9 = 63
7 ร 10 = 70
Program 2: Number guessing game (input-based).
Set secret to 42.
Set guesses to 0.
Set found to false.
Display "I'm thinking of a number between 1 and 100.".
Display "".
While not found:
Ask "Your guess: " and store in guess.
Convert guess to a number.
Increase guesses by 1.
If guess is equal to secret:
Display "๐ Correct! You got it in " plus guesses plus " guesses!".
Set found to true.
Otherwise if guess is less than secret:
Display "Too low. Try again.".
Otherwise:
Display "Too high. Try again.".
End if.
End while.
Sample Run:
I'm thinking of a number between 1 and 100.
Your guess: 50
Too high. Try again.
Your guess: 25
Too low. Try again.
Your guess: 42
๐ Correct! You got it in 3 guesses!
Program 3: Sum of N numbers (input-based).
Ask "How many numbers do you want to add? " and store in count.
Convert count to a number.
Set total to 0.
Repeat from 1 to count as i:
Ask "Enter a number: " and store in num.
Convert num to a number.
Set total to total plus num.
End repeat.
Display "".
Display "Sum of " plus count plus " numbers = " plus total.
Display "Average = " plus round(total divided by count, 2).
Sample Run:
How many numbers do you want to add? 4
Enter number 1: 10
Enter number 2: 25
Enter number 3: 30
Enter number 4: 15
Sum of 4 numbers = 80
Average = 20.0
Program 4: Pattern printer (input-based).
Ask "Enter number of rows: " and store in rows.
Convert rows to a number.
Display "".
Repeat from 1 to rows as i:
Set line to "".
Repeat from 1 to i as j:
Set line to line plus "โ
".
End repeat.
Display line.
End repeat.
Sample Run:
Enter number of rows: 5
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Chapter 6: Functions
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Definition: Functions are reusable blocks of code that perform a specific task and can be called multiple times within a program.
Explanation: In UNEL, functions help organize code, reduce repetition, and improve readability. They can accept inputs (parameters), process data, and optionally return results, making programs modular and easier to maintain.
6.1 Defining Functions
Definition: Defining functions is the process of creating a named block of reusable code that performs a specific task.
Explanation: In UNEL, functions are defined using a clear, English-like structure that specifies the function name and optionally its parameters. Once defined, the function can be called multiple times, promoting code reuse and organization.
What is a Function?
Definition: A function is a named, reusable block of code that performs a specific task and can be called by name from anywhere in the program.
A function is a reusable block of code that performs a specific task. In UNEL, function definitions read like English:
Define function say_hello:
Display "Hello from a function!".
End function.
Note: Call the function.
say_hello().
Output:
Hello from a function!
Functions with Parameters
Definition: Functions with parameters accept input values when called, allowing the same function to operate on different data each time.
Define function greet that takes name:
Display "Hello, " plus name plus "! Welcome to UNEL.".
End function.
greet("Alice").
greet("Bob").
greet("Charlie").
Output:
Hello, Alice! Welcome to UNEL.
Hello, Bob! Welcome to UNEL.
Hello, Charlie! Welcome to UNEL.
Functions with Return Values
Definition: Functions with return values produce output using the Return statement, sending a result back to the code that called the function.
Define function total_of that takes a and b:
Return a plus b.
End function.
Set result to total_of(10, 20).
Display "10 + 20 = " plus result.
Multiple Parameters
Definition: Functions with multiple parameters accept two or more input values, separated by 'and' in the function definition.
Define function calculate_area that takes the_length and the_width:
Return the_length multiplied by the_width.
End function.
Define function calculate_perimeter that takes the_length and the_width:
Return 2 multiplied by (the_length plus the_width).
End function.
Set area to calculate_area(12, 8).
Set perimeter to calculate_perimeter(12, 8).
Display "Rectangle 12ร8:".
Display " Area: " plus area.
Display " Perimeter: " plus perimeter.
Output:
Rectangle 12ร8:
6.2 Control Flow in Functions
Definition: Control flow refers to the order in which statements and instructions are executed in a program.
Explanation: In UNEL, control flow is managed using constructs such as conditionals, loops, and function returns. These determine how the program progresses, allowing it to make decisions, repeat actions, or exit early based on conditions.
Early Return
Definition: Early return exits a function before reaching its end, typically used inside conditional statements to handle special cases or guard clauses.
Define function get_grade that takes marks:
If marks is greater than or equal to 90:
Return "A+".
End if.
If marks is greater than or equal to 80:
Return "A".
End if.
If marks is greater than or equal to 70:
Return "B".
End if.
If marks is greater than or equal to 60:
Return "C".
End if.
Return "F".
End function.
Display "85 โ " plus get_grade(85). Note: A
Display "72 โ " plus get_grade(72). Note: B
Display "55 โ " plus get_grade(55). Note: F
Output:
A
B
F
Functions Calling Other Functions
Definition: Functions can call other functions to build complex behavior from simpler, reusable parts, promoting modular and organized code.
Define function square that takes n:
Return n multiplied by n.
End function.
Define function cube that takes n:
Return n multiplied by square(n).
End function.
Define function hypotenuse that takes a and b:
Return sqrt(square(a) plus square(b)).
End function.
Display "5ยฒ = " plus square(5). Note: 25
Display "3ยณ = " plus cube(3). Note: 27
Display "hyp(3,4) = " plus hypotenuse(3, 4). Note: 5.0
Output:
25
27
5.0
6.3 Variable Scope
Definition: Variable scope refers to the region of a program where a variable is accessible and can be used.
Explanation: In UNEL, variables defined inside a function are local and exist only within that function, while variables defined outside are global and accessible throughout the program. Local variables do not affect global variables with the same name.
Local Variables
Definition: Local variables are declared inside a function and exist only within that function's scope, invisible to code outside the function.
Variables defined inside a function are local โ they exist only inside that function:
Define function calculate:
Set result to 42. Note: 'result' exists only inside this function.
Display "Inside function: " plus result.
End function.
calculate().
Note: Display result. โ This would cause an error!
Note: 'result' does not exist outside the function.
Global vs Local
Definition: Global variables are accessible throughout the entire program, while local variables exist only within their defining function and take precedence when names conflict.
Set message to "I am global".
Define function show_message:
Set message to "I am local".
Display "Inside: " plus message.
End function.
Display "Before: " plus message.
show_message().
Display "After: " plus message.
Output:
Before: I am global
Inside: I am local
After: I am global
The function creates its OWN message โ it does not change the global one.
6.4 Parameters
Definition: Parameters are variables defined in a function that receive values when the function is called.
Explanation: In UNEL, parameters allow functions to accept input and operate on different data each time they are called. They make functions flexible and reusable by enabling dynamic behavior based on the provided arguments.
Typed Parameters
Definition: Typed parameters specify the expected data type of each function argument, providing documentation and type safety for function inputs.
Define function calculate_bmi that takes decimal weight and decimal height:
Return round(weight divided by (height multiplied by height), 1).
End function.
Display "BMI: " plus calculate_bmi(70, 1.75). Note: 22.9
Output:
22.9
Default Parameter Values
Definition: Default parameter values provide fallback values for function arguments, allowing callers to omit optional parameters.
Define function greet that takes name and greeting:
Display greeting plus ", " plus name plus "!".
End function.
greet("Alice", "Hello").
greet("Bob", "Good morning").
greet("Charlie", "Hey").
Multiple Parameters
Definition: Functions with multiple parameters accept two or more input values, separated by 'and' in the function definition.
Define function create_profile that takes name and age and city:
Display "Name: " plus name plus ", Age: " plus age plus ", City: " plus city.
End function.
create_profile("Alice", 25, "Mumbai").
create_profile("Bob", 30, "Delhi").
6.5 Return Values
Definition: Return values are the results produced by a function and sent back to the point where the function was called.
Explanation: In UNEL, a function uses the Return statement to provide output after performing its task. The returned value can then be stored, displayed, or used in further computations.
Returning a Single Value
Definition: Returning a single value sends one result back to the caller using the Return statement, which can then be stored or used in expressions.
Define function celsius_to_fahrenheit that takes c:
Return (c multiplied by 9 divided by 5) plus 32.
End function.
Display "100ยฐC = " plus celsius_to_fahrenheit(100) plus "ยฐF".
Display "0ยฐC = " plus celsius_to_fahrenheit(0) plus "ยฐF".
Returning Multiple Values
Definition: Returning multiple values allows a function to send back several results at once, which can be unpacked into separate variables by the caller.
Define function find_max that takes numbers:
Set maximum to numbers[1].
For each current in numbers:
If current is greater than maximum:
Set maximum to current.
End if.
End for.
Return maximum.
End function.
Set highest to find_max([34, 12, 78, 5, 91, 23]).
Display "Max: " plus highest.
Returning Nothing
Definition: A function that returns nothing performs an action (like displaying output) without producing a value, equivalent to a void function.
Define function validate_age that takes age:
If age is less than 0 or age is greater than 150:
Display "Invalid age: " plus age.
Return nothing.
End if.
Return age.
End function.
Set valid to validate_age(25).
Set invalid to validate_age(-5).
Display "Valid: " plus valid. Note: 25
Display "Invalid: " plus invalid. Note: nothing
Output:
25
nothing
6.6 Keyword Arguments
Definition: Keyword arguments are arguments passed to a function by explicitly specifying the parameter names along with their values.
Explanation: In UNEL, keyword arguments improve readability and clarity by making it clear which value corresponds to which parameter. They also allow arguments to be passed in any order and support default parameter values for flexible function calls.
Lambda Functions (Anonymous Functions)
Definition: Lambda functions are small, anonymous functions defined in a single line using the lambda keyword, useful for simple operations and callbacks.
Set double to lambda x: x multiplied by 2.
Set addition to lambda a, b: a plus b.
Display double(5).
Display addition(3, 4).
Output:
10
7
Higher-Order Functions
Definition: Higher-order list functions include map(), filter(), and reduce() which apply transformations, selections, and aggregations to list data.
Functions that accept other functions as arguments:
Set numbers to [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].
Set doubled to map(numbers, lambda x: x multiplied by 2).
Display "Doubled: " plus doubled.
Set evens to filter(numbers, lambda x: mod(x, 2) is equal to 0).
Display "Evens: " plus evens.
Set total to reduce(numbers, lambda acc, x: acc plus x, 0).
Display "Sum: " plus total.
๐ Try It Yourself โ Interactive Programs
Definition: Interactive programs are input-based exercises using the Ask statement that allow learners to practice building dynamic, user-driven applications.
Program 1: Calculator with functions (input-based).
Define function total_of that takes a and b:
Return a plus b.
End function.
Define function subtract that takes a and b:
Return a minus b.
End function.
Define function product_of that takes a and b:
Return a multiplied by b.
End function.
Define function quotient_of that takes a and b:
If b is equal to 0:
Return "Error: Division by zero".
End if.
Return a divided by b.
End function.
Ask "Enter first number: " and store in x.
Ask "Enter second number: " and store in y.
Convert x to a number.
Convert y to a number.
Display "".
Display x plus " + " plus y plus " = " plus total_of(x, y).
Display x plus " - " plus y plus " = " plus subtract(x, y).
Display x plus " ร " plus y plus " = " plus product_of(x, y).
Display x plus " รท " plus y plus " = " plus quotient_of(x, y).
Sample Run:
Enter first number: 24
Enter second number: 6
24 + 6 = 30
24 - 6 = 18
24 ร 6 = 144
24 รท 6 = 4
Program 2: Prime number checker (input-based).
Define function is_prime that takes num:
If num is less than or equal to 1:
Return false.
End if.
Set divisor to 2.
While divisor is less than or equal to floor(sqrt(num)):
If mod(amount, divisor) is equal to 0:
Return false.
End if.
Increase divisor by 1.
End while.
Return true.
End function.
Ask "Enter a number: " and store in n.
Convert n to a number.
If is_prime(n):
Display n plus " is a prime number.".
Otherwise:
Display n plus " is not a prime number.".
End if.
Sample Run:
Enter a number: 47
47 is a prime number.
Program 3: Fibonacci generator (input-based).
Define function fibonacci that takes n:
If n is less than or equal to 0:
Return 0.
End if.
If n is equal to 1:
Return 1.
End if.
Set current to 0.
Set following to 1.
Repeat from 2 to n as i:
Set next to current plus following.
Set current to following.
Set following to next.
End repeat.
Return following.
End function.
Ask "How many Fibonacci numbers? " and store in count.
Convert count to a number.
Display "".
Set result to "".
Repeat from 0 to count minus 1 as i:
Set result to result plus fibonacci(i).
If i is less than count minus 1:
Set result to result plus ", ".
End if.
End repeat.
Display "Fibonacci: " plus result.
Sample Run:
How many Fibonacci numbers? 10
Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Chapter 7: Modules
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
7.1 Module Basics
Definition: Modules are collections of related functions, constants, and utilities that can be imported and used in a program.
Explanation: In UNEL, modules help organize code and provide reusable functionality. By importing a module, programs can access predefined operations such as mathematical calculations or text processing, making development more efficient and structured.
What is a Module?
Definition: A module is a file containing related functions, constants, and utilities that can be imported into any UNEL program to extend its capabilities.
A module is a package of related functions and constants that you can use in your program. Modules help organize code and provide commonly needed functionality.
The Math Module
Definition: The Math module provides mathematical functions and constants including PI, e, trigonometric functions, logarithms, and power calculations.
Import Math.
Display "Pi: " plus Math.PI.
Display "E: " plus Math.E.
Display "sqrt(16): " plus Math.sqrt(16).
Display "sin(0): " plus Math.sin(0).
Display "cos(0): " plus Math.cos(0).
Display "abs(-5): " plus Math.abs(-5).
Output:
Pi: 3.141592653589793
E: 2.718281828459045
sqrt(16): 4.0
sin(0): 0.0
cos(0): 1.0
abs(-5): 5
7.2 Importing Names
Definition: Importing names is the process of bringing a module or its contents into a program so they can be used.
Explanation: In UNEL, modules can be imported directly or with an alias to simplify usage. This allows access to functions and constants defined in the module, improving code organization and readability.
Import with Alias
Definition: Importing with an alias assigns a shorter name to a module using 'as', making subsequent references more concise and readable.
Import Math as M.
Display M.sqrt(144). Note: 12
Display power(2, 8). Note: 256
Display M.PI. Note: 3.14159...
Output:
12
256
3.14159...
Using Module Constants
Definition: Module constants are predefined values like PI and e that are accessed through the module name after importing.
Import Math.
Constant PI is Math.PI.
Set radius to 10.
Set area to PI multiplied by radius multiplied by radius.
Display "Circle area: " plus round(area, 2).
7.3 The Help System
Definition: The help system is a built-in feature that provides information about available functions, modules, and their usage within the language.
Explanation: In UNEL, the help system allows users to discover and understand built-in capabilities without external references. It lists functions, categories, and their purposes, making it easier to learn and use the language effectively.
Built-in Functions Available Without Import
Definition: Built-in functions are core operations available without any import statement, including Display, length(), round(), and type conversion functions.
UNEL provides many functions without needing any import:
| Category | Functions |
|---|---|
| Math | abs, sqrt, power, round, floor, ceil, mod, min, max, random |
| String | length, uppercase, lowercase, trim, contains, replace, split, join |
| List | sort, reverse, unique, flatten, map, filter, reduce |
| Type | typeof, to_integer, to_decimal, to_text, to_boolean |
| Utility | range, enumerate, zip, deep_copy |
7.4 Finding Modules
Definition: Finding modules refers to identifying and accessing available built-in modules that provide additional functionality for a program.
Explanation: In UNEL, modules can be explored through the help system or documentation, allowing users to discover useful libraries such as Math, Text, and List. This helps programmers extend their programs by using predefined and organized features.
Available Built-in Modules
Definition: Available built-in modules list all the standard modules that come with UNEL, including Math, Text, List, and their contained functions.
| Module | Description | Key Functions |
|---|---|---|
Math |
Mathematics | sqrt, sin, cos, tan, PI, E, abs, power |
Text |
Text utilities | uppercase, lowercase, trim, split, replace |
List |
List utilities | sort, reverse, unique, flatten, chunk |
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Chapter 8: Strings (In Depth)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Definition: A string is a data type that represents a sequence of characters enclosed in double quotes.
Explanation: In UNEL, strings are used to store and manipulate text. They support various operations such as concatenation, slicing, searching, and formatting, making them essential for handling textual data in programs.
8.1 String Operations
Definition: String operations are the set of functions and actions used to manipulate and analyze text data.
Explanation: In UNEL, string operations include tasks such as changing case, trimming whitespace, reversing text, searching for substrings, and combining or splitting strings. These operations enable flexible and efficient handling of textual data.
Complete String Function Reference
Definition: The complete string function reference catalogs every built-in string operation with syntax, description, and usage examples.
Set message to "Hello, World!".
Display "Original: " plus message.
Display "Length: " plus length(message).
Display "Uppercase: " plus uppercase(message).
Display "Lowercase: " plus lowercase(message).
Display "Capitalize: " plus capitalize("hello world").
Display "Reversed: " plus reverse(message).
Display "Repeated: " plus repeat_string("Ha", 3).
Display "Trimmed: " plus trim(" hello ").
Display "Word count: " plus word_count(message).
Output:
Original: Hello, World!
Length: 13
Uppercase: HELLO, WORLD!
Lowercase: hello, world!
Capitalize: Hello world
Reversed: !dlroW ,olleH
Repeated: HaHaHa
Trimmed: hello
Word count: 2
8.2 String Slicing
Definition: String slicing is the process of extracting a portion of a string based on specified positions.
Explanation: In UNEL, slicing is performed using functions like substring(), which allow selecting characters from a starting position to an ending position. It uses 1-based indexing and can also extract text from a given position to the end of the string.
Extracting Substrings
Definition: The substring() function extracts a portion of a string between specified start and end positions using 1-based indexing.
Set message to "Hello, World!".
Display substring(message, 1, 5). Note: Hello
Display substring(message, 8, 12). Note: World
Display substring(message, 8). Note: World!
Output:
Hello
World
World!
Character Access
Definition: Character access retrieves individual characters from a string using their position number, with 1 being the first character.
Set word to "PROGRAMMING".
Repeat from 1 to length(word) as i:
Display "Position " plus i plus ": " plus char_at(word, i).
End repeat.
8.3 Searching and Testing Strings
Definition: Searching and testing strings involve checking for the presence, position, or properties of specific text within a string.
Explanation: In UNEL, these operations include functions to determine whether a substring exists, whether a string starts or ends with certain text, and to find the position of a substring. They also include checks for properties like uppercase or lowercase, enabling validation and analysis of text data.
Finding Substrings
Definition: Finding substrings uses functions like index_of() and contains() to locate text within a string and determine if it exists.
Set message to "The quick brown fox jumps over the lazy dog".
Display "Contains 'fox': " plus contains(message, "fox"). Note: true
Display "Contains 'cat': " plus contains(message, "cat"). Note: false
Display "Starts with 'The': " plus starts_with(message, "The"). Note: true
Display "Ends with 'dog': " plus ends_with(message, "dog"). Note: true
Display "Index of 'fox': " plus index_of(message, "fox"). Note: 17
Output:
true
false
true
true
17
Testing String Properties
Definition: Testing string properties uses boolean functions like is_upper(), is_lower(), is_digit(), and is_alpha() to check character characteristics.
Display is_upper("HELLO"). Note: true
Display is_upper("Hello"). Note: false
Display is_lower("hello"). Note: true
Display is_lower("Hello"). Note: false
Output:
true
false
true
false
Counting Characters
Definition: The count() function returns the number of times a specific substring appears within a string.
Set message to "Mississippi".
Display "Count of 's': " plus count_char(message, "s"). Note: 4
Display "Count of 'i': " plus count_char(message, "i"). Note: 4
Display "Count of 'p': " plus count_char(message, "p"). Note: 2
Output:
4
4
2
8.4 String Formatting
Definition: String formatting is the process of arranging and presenting text in a structured and readable form, often by inserting values into a string.
Explanation: In UNEL, string formatting includes techniques such as interpolation and padding, which allow dynamic insertion of variables and alignment of text. This helps produce clean, organized, and visually appealing output.
String Interpolation
Definition: String interpolation in depth shows advanced usage of curly braces {} to embed complex expressions and multiple variables within formatted strings.
Set name to "Jayaram".
Set score to 95.
Set grade to "A+".
Display "{name} scored {score} marks and received grade {grade}.".
Output:
{name} scored {score} marks and received grade {grade}.
Padding and Alignment
Definition: Padding functions (pad_left, pad_right, center) add characters to align text within a specified width for formatted output.
Note: Left-align names, right-align scores.
Set names to ["Alice", "Bob", "Charlie", "Diana"].
Set scores to [92, 78, 85, 95].
Display repeat_string("โ", 25).
Repeat from 1 to length(names) as i:
Set name_col to pad_right(names[i], 12, " ").
Set score_col to pad_left(to_text(scores[i]), 5, " ").
Display name_col plus score_col.
End repeat.
Display repeat_string("โ", 25).
8.5 Splitting and Joining Strings
Definition: Splitting and joining strings are operations used to convert between a single string and a list of strings.
Explanation: In UNEL, splitting divides a string into parts based on a delimiter, while joining combines multiple strings into one using a specified separator. These operations are essential for processing structured text data such as CSV, sentences, and multi-line input.
Split a String into a List
Definition: The split() function divides a string into a list of substrings based on a specified delimiter character or pattern.
Set csv_data to "Alice,25,Mumbai,Engineering".
Set parts to split(csv_data, ",").
Display "Name: " plus parts[1].
Display "Age: " plus parts[2].
Display "City: " plus parts[3].
Display "Major: " plus parts[4].
Join a List into a String
Definition: The join() function combines a list of strings into a single string, placing a specified separator between each element.
Set words to ["UNEL", "is", "a", "natural", "language"].
Set sentence to join(words, " ").
Display sentence. Note: UNEL is a natural language
Output:
UNEL is a natural language
Splitting into Words
Definition: The words() function splits a string into a list of individual words, using whitespace as the delimiter.
Set sentence to "The quick brown fox".
Set word_list to words(sentence).
Display "Words: " plus word_list.
Display "Word count: " plus word_count(sentence).
Splitting into Lines
Definition: The split_lines() function divides a multi-line string into a list of individual lines.
Set multiline to "Line 1\nLine 2\nLine 3".
Set lines to split_lines(multiline).
For each line in lines:
Display ">> " plus line.
End for.
Practical Program: CSV Parser
Definition: The CSV parser demonstrates real-world string splitting and joining to process comma-separated data into structured output.
Note: Parse and display CSV data.
Set csv to "Name,Subject,Marks\nAlice,Math,92\nBob,Science,88\nCharlie,English,95".
Set rows to split_lines(csv).
Note: Display header.
Set header to split(rows[1], ",").
Display pad_right(header[1], 10, " ") plus pad_right(header[2], 12, " ") plus header[3].
Display repeat_string("โ", 28).
Note: Display data rows.
Repeat from 2 to length(rows) as i:
Set cols to split(rows[i], ",").
Display pad_right(cols[1], 10, " ") plus pad_right(cols[2], 12, " ") plus cols[3].
End repeat.
๐ Try It Yourself โ Interactive Programs
Definition: Interactive programs are input-based exercises using the Ask statement that allow learners to practice building dynamic, user-driven applications.
Program 1: Word reverser (input-based).
Ask "Enter a sentence: " and store in sentence.
Set word_list to split(sentence, " ").
Set reversed_words to reverse(word_list).
Set reversed_sentence to join(reversed_words, " ").
Display "".
Display "Original: " plus sentence.
Display "Reversed: " plus reversed_sentence.
Display "Words: " plus word_list.
Display "Count: " plus length(word_list) plus " words".
Sample Run:
Enter a sentence: UNEL is programming in English
Original: UNEL is programming in English
Reversed: English in programming is UNEL
Words: [UNEL, is, programming, in, English]
Count: 5 words
Program 2: Vowel counter (input-based).
Ask "Enter a word: " and store in word.
Set vowels to "aeiouAEIOU".
Set vowel_count to 0.
Repeat from 1 to length(word) as i:
Set ch to char_at(word, i).
If contains(vowels, ch):
Increase vowel_count by 1.
End if.
End repeat.
Display "".
Display "Word: " plus word.
Display "Vowels: " plus vowel_count.
Display "Length: " plus length(word).
Sample Run:
Enter a word: Programming
Word: Programming
Vowels: 3
Length: 11
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Chapter 9: Lists (In Depth)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
9.1 Modifying and Iterating Lists
Definition: Modifying and iterating lists refer to the processes of changing list elements and traversing through each item in a list.
Explanation: In UNEL, lists can be modified by adding, removing, or updating elements using their positions. Iteration allows accessing each element one by one using loops, enabling operations such as calculations, transformations, and data processing.
Adding Items
Definition: The Add statement appends a new item to the end of a list, growing the collection by one element.
Set fruits to ["Apple", "Banana"].
Display "Before: " plus fruits.
Add "Cherry" to fruits.
Add "Date" to fruits.
Display "After: " plus fruits.
Removing Items
Definition: The Remove statement deletes an item from a list by its value, shrinking the collection by one element.
Set numbers to [10, 20, 30, 40, 50].
Display "Before: " plus numbers.
Remove item 3 from numbers.
Display "After removing item 3: " plus numbers.
Modifying Items by Index
Definition: Modifying items by index assigns a new value to a specific position in a list using bracket notation.
Set colors to ["Red", "Green", "Blue"].
Set colors[2] to "Purple".
Display colors. Note: [Red, Purple, Blue]
Output:
[Red, Purple, Blue]
Iterating with Index
Definition: Iterating with index uses 'For each item at position index' to access both the element and its positional number during traversal.
Set names to ["Alice", "Bob", "Charlie", "Diana"].
Repeat from 1 to length(names) as i:
Display "Student " plus i plus ": " plus names[i].
End repeat.
Using For Each
Definition: The For Each loop provides the simplest way to process every element in a list without needing to manage index numbers manually.
Set prices to [100, 250, 75, 300, 150].
Set total to 0.
For each price in prices:
Set total to total plus price.
End for.
Display "Total: โน" plus total.
Display "Average: โน" plus (total divided by length(prices)).
9.2 Sorting and Reversing Lists
Definition: Sorting and reversing lists are operations used to arrange list elements in a specific order or to invert their sequence.
Explanation: In UNEL, sorting organizes elements in ascending order (or based on custom logic), while reversing changes the order of elements from last to first. These operations help in organizing and analyzing data efficiently.
Basic Sorting
Definition: The sort() function arranges list elements in ascending order, returning a new sorted list without modifying the original.
Set numbers to [64, 34, 25, 12, 22, 11, 90].
Display "Unsorted: " plus numbers.
Set sorted_nums to sort(numbers).
Display "Sorted: " plus sorted_nums.
Set reversed_nums to reverse(sorted_nums).
Display "Reversed: " plus reversed_nums.
Sorting Strings
Definition: Sorting strings arranges text elements in alphabetical order, with uppercase letters sorted before lowercase by default.
Set names to ["Charlie", "Alice", "Eve", "Bob", "Diana"].
Set sorted_names to sort(names).
Display "Sorted: " plus sorted_names.
Output:
Sorted: [Alice, Bob, Charlie, Diana, Eve]
Custom Sorting with sort_by
Definition: The sort_by() function sorts a list using a custom comparison function, allowing ordering by length, specific properties, or custom criteria.
Set students to [
{"name": "Charlie", "marks": 78},
{"name": "Alice", "marks": 92},
{"name": "Bob", "marks": 85}
].
Set by_marks to sort_by(students, lambda s: s["marks"]).
For each s in by_marks:
Display s["name"] plus ": " plus s["marks"].
End for.
Output:
Charlie: 78
Bob: 85
Alice: 92
9.3 Common List Operations
Definition: Common list operations are standard functions and actions used to manipulate, analyze, and manage elements within a list.
Explanation: In UNEL, these operations include searching for elements, calculating statistics, combining lists, removing duplicates, flattening nested lists, and extracting portions of a list. They enable efficient handling and transformation of collection data.
Searching
Definition: List searching uses functions like contains(), index_of(), and count() to find elements and determine their positions within a list.
Set fruits to ["apple", "banana", "cherry", "date"].
Display "Contains 'banana': " plus contains(fruits, "banana").
Display "Contains 'grape': " plus contains(fruits, "grape").
Display "Index of 'cherry': " plus index_of(fruits, "cherry").
Output:
true
false
3
Statistical Functions
Definition: Statistical functions like sum(), min(), max(), and average calculations provide quick numerical analysis of list data.
Set scores to [85, 92, 78, 95, 88, 76, 91].
Display "Sum: " plus sum(scores).
Display "Average: " plus average(scores).
Display "Min: " plus min(scores).
Display "Max: " plus max(scores).
Display "Length: " plus length(scores).
Combining Lists
Definition: Combining lists merges two or more lists into a single list using concatenation with the plus operator.
Set first to [1, 2, 3].
Set second to [4, 5, 6].
Set combined to first plus second.
Display "Combined: " plus combined. Note: [1, 2, 3, 4, 5, 6]
Note: Using spread operator.
Set merged to [...first, 0, ...second].
Display "Merged: " plus merged. Note: [1, 2, 3, 0, 4, 5, 6]
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 0, 4, 5, 6]
Unique and Flatten
Definition: The unique() function removes duplicate elements, while flatten() converts nested lists into a single-level list.
Set duplicates to [1, 2, 2, 3, 3, 3, 4].
Display "Unique: " plus unique(duplicates). Note: [1, 2, 3, 4]
Set nested to [[1, 2], [3, 4], [5, 6]].
Display "Flattened: " plus flatten(nested). Note: [1, 2, 3, 4, 5, 6]
Output:
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6]
Slicing
Definition: List slicing extracts a portion of a list between specified start and end positions, creating a new sub-list.
Set numbers to [10, 20, 30, 40, 50, 60, 70].
Display "First 3: " plus take(numbers, 3). Note: [10, 20, 30]
Display "Skip 3: " plus drop(numbers, 3). Note: [40, 50, 60, 70]
Display "Slice 2-5: " plus slice(numbers, 2, 5). Note: [20, 30, 40, 50]
Output:
[10, 20, 30]
[40, 50, 60, 70]
[20, 30, 40, 50]
9.4 Nested Lists
Definition: Nested lists are lists that contain other lists as their elements, allowing representation of multi-dimensional data.
Explanation: In UNEL, nested lists are used to model structures like matrices, tables, or grids. Accessing elements requires multiple indices, and operations often involve nested loops to process rows and columns.
2D Lists (Matrix)
Definition: 2D lists (matrices) are lists of lists used to represent tabular data, grids, and mathematical matrices with row and column access.
Set matrix to [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
].
Display "Element at row 2, col 3: " plus matrix[2][3]. Note: 6
Note: Print the matrix.
For each row in matrix:
Set line to "".
For each val in row:
Set line to line plus pad_left(to_text(val), 4, " ").
End for.
Display line.
End for.
Output:
6
Practical: Matrix Addition
Definition: Matrix addition demonstrates nested list processing by adding corresponding elements of two matrices to produce a result matrix.
Set A to [[1, 2, 3], [4, 5, 6]].
Set B to [[7, 8, 9], [10, 11, 12]].
Set C to [].
Repeat from 1 to length(A) as i:
Set row to [].
Repeat from 1 to length(A[i]) as j:
Add (A[i][j] plus B[i][j]) to row.
End repeat.
Add row to C.
End repeat.
Display "A + B = " plus C. Note: [[8, 10, 12], [14, 16, 18]]
Output:
[[8, 10, 12], [14, 16, 18]]
9.5 List Comprehensions
Definition: List comprehensions are a concise way to create and transform lists using a single, expressive statement.
Explanation: In UNEL, list comprehensions combine iteration and optional filtering to generate lists efficiently. They improve readability and reduce the need for explicit loops when performing transformations or selections on data.
Basic Comprehension
Definition: Basic list comprehension creates a new list by applying an expression to each element of an existing collection in a single statement.
Set squares to [x multiplied by x for each x in range(1, 10)].
Display "Squares: " plus squares.
With Filter Condition
Definition: Filtered comprehension adds a condition to select only elements that meet specified criteria, combining transformation and filtering.
Set evens to [x for each x in range(1, 20) if mod(x, 2) is equal to 0].
Display "Even numbers: " plus evens.
Output:
Even numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Map, Filter, Reduce
Definition: Map transforms each element, Filter selects elements matching a condition, and Reduce combines all elements into a single value โ three fundamental higher-order list operations.
Set numbers to [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].
Set doubled to map(numbers, lambda x: x multiplied by 2).
Display "Doubled: " plus doubled.
Set big to filter(numbers, lambda x: x is greater than 5).
Display "Greater than 5: " plus big.
Set total to reduce(numbers, lambda acc, x: acc plus x, 0).
Display "Sum: " plus total.
Output:
Doubled: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Greater than 5: [6, 7, 8, 9, 10]
Sum: 55
๐ Try It Yourself โ Interactive Programs
Definition: Interactive programs are input-based exercises using the Ask statement that allow learners to practice building dynamic, user-driven applications.
Program 1: Marks list manager (input-based).
Set marks to [].
Ask "How many subjects? " and store in count.
Convert count to a number.
Repeat from 1 to count as i:
Ask "Enter marks: " and store in m.
Convert m to a number.
Add m to marks.
End repeat.
Set marks_sorted to sort(marks).
Display "".
Display "โโโ Result โโโ".
Display "Marks: " plus marks.
Display "Sorted: " plus marks_sorted.
Display "Highest: " plus max(marks).
Display "Lowest: " plus min(marks).
Display "Total: " plus sum(marks).
Display "Average: " plus round(average(marks), 1).
Sample Run:
How many subjects? 5
Enter marks for subject 1: 85
Enter marks for subject 2: 92
Enter marks for subject 3: 78
Enter marks for subject 4: 95
Enter marks for subject 5: 88
โโโ Result โโโ
Marks: [85, 92, 78, 95, 88]
Sorted: [78, 85, 88, 92, 95]
Highest: 95
Lowest: 78
Total: 438
Average: 87.6
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Chapter 10: Dictionaries
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
10.1 Dictionary Basics
Definition: A dictionary is a data structure that stores values as key-value pairs, where each key uniquely identifies its associated value.
Explanation: In UNEL, dictionaries are used to represent structured and labeled data. They allow efficient access, modification, and organization of information using keys, making them suitable for representing real-world entities and records.
What is a Dictionary?
Definition: A dictionary is a key-value data structure where each unique key maps to an associated value, providing labeled access to data.
A dictionary stores data as key-value pairs. Each key maps to a value:
Set student to {"name": "Alice", "age": 20, "gpa": 3.8}.
Display student.
Display "Name: " plus student["name"].
Display "Age: " plus student["age"].
Display "GPA: " plus student["gpa"].
Output:
{name: Alice, age: 20, gpa: 3.8}
Name: Alice
Age: 20
GPA: 3.8
10.2 Dictionary Creation
Definition: Dictionary creation is the process of defining and initializing a dictionary with key-value pairs.
Explanation: In UNEL, dictionaries are created using curly braces {} with keys mapped to values. Entries can be added or modified after creation, allowing flexible and dynamic data organization.
Creating Dictionaries
Definition: Dictionaries are created using curly braces with key-value pairs separated by colons, like '{"name": "Alice", "age": 25}'.
Note: Empty dictionary.
Set empty to {}.
Note: Student record.
Set student to {
"name": "Jayaram",
"roll_number": 42,
"branch": "Computer Science",
"semester": 6,
"cgpa": 8.5
}.
Display student.
Output:
{name: Jayaram, roll_number: 42, branch: Computer Science, semester: 6, cgpa: 8.5}
Adding and Modifying Entries
Definition: New entries are added by assigning to a new key, and existing entries are modified by assigning a new value to an existing key.
Set person to {"name": "Alice", "age": 25}.
Note: Add a new key.
Set person["city"] to "Mumbai".
Note: Modify an existing key.
Set person["age"] to 26.
Display person.
Output:
{name: Alice, age: 26, city: Mumbai}
10.3 Dictionary Operations
Definition: Dictionary operations are the set of actions used to access, modify, and manage key-value pairs within a dictionary.
Explanation: In UNEL, these operations include retrieving values using keys, adding new entries, updating existing values, removing entries, and iterating over keys and values. They enable efficient manipulation of structured data.
Checking Keys
Definition: The has_key() function checks whether a specific key exists in a dictionary, returning true or false.
Set config to {"theme": "dark", "language": "English", "font_size": 14}.
Display "Has 'theme': " plus has_key(config, "theme"). Note: true
Display "Has 'color': " plus has_key(config, "color"). Note: false
Output:
true
false
Getting Keys and Values
Definition: The keys() and values() functions return lists of all keys or all values in a dictionary for iteration or inspection.
Set scores to {"math": 90, "science": 85, "english": 92}.
Display "Keys: " plus keys(scores). Note: ["math", "science", "english"]
Display "Values: " plus values(scores). Note: [90, 85, 92]
Display "Size: " plus length(scores). Note: 3
Output:
["math", "science", "english"]
[90, 85, 92]
3
Removing Entries
Definition: The remove_key() function deletes a key-value pair from a dictionary by specifying the key to remove.
Set data to {"a": 1, "b": 2, "c": 3}.
Display "Before: " plus data.
Set data to {"a": 1, "c": 3}.
Display "After: " plus data.
Output:
{"a": 1, "c": 3}
10.4 Conditionals and Looping in Dictionaries
Definition: Conditional and looping in dictionaries refer to applying decision-making and iteration over key-value pairs within a dictionary.
Explanation: In UNEL, loops are used to traverse through each key and value in a dictionary, while conditional statements allow filtering or processing entries based on specific conditions. This enables selective access, validation, and transformation of structured data.
Iterating Over a Dictionary
Definition: Iterating over a dictionary uses For Each to traverse all key-value pairs, providing access to both keys and values.
Set inventory to {"Apples": 50, "Bananas": 30, "Oranges": 45, "Grapes": 20}.
Display "โโโ Inventory โโโ".
For each fruit, quantity in inventory:
Display " " plus fruit plus ": " plus quantity.
End for.
Output:
โโโ Inventory โโโ
Conditional Logic with Dictionaries
Definition: Conditional logic with dictionaries uses If statements to check key existence, validate values, or filter entries based on criteria.
Set grades to {"Alice": 92, "Bob": 78, "Charlie": 85, "Diana": 95}.
Set honor_students to [].
For each name, grade in grades:
If grade is greater than or equal to 90:
Add name to honor_students.
End if.
End for.
Display "Honor Roll: " plus honor_students.
10.5 Nested Dictionaries and Dictionary Comprehension
Definition: Nested dictionaries are dictionaries that contain other dictionaries as values, while dictionary comprehension is a concise way to create dictionaries using a single expression.
Explanation: In UNEL, nested dictionaries are used to represent complex, hierarchical data structures. Dictionary comprehension allows efficient construction of dictionaries by combining iteration and optional conditions, making code shorter and more expressive.
Nested Dictionaries
Definition: Nested dictionaries contain dictionaries as values, allowing hierarchical data structures like records within categories.
Set school to {
"class_10a": {
"teacher": "Mrs. Smith",
"students": 35,
"subjects": ["Math", "Science", "English"]
},
"class_10b": {
"teacher": "Mr. Jones",
"students": 32,
"subjects": ["Math", "Science", "History"]
}
}.
Display "10A Teacher: " plus school["class_10a"]["teacher"].
Display "10B Students: " plus school["class_10b"]["students"].
Display "10A Subjects: " plus school["class_10a"]["subjects"].
Building a Student Database
Definition: A student database program demonstrates dictionary creation, modification, and iteration to manage structured student records.
Set students to [
{"name": "Alice", "math": 92, "science": 88, "english": 95},
{"name": "Bob", "math": 78, "science": 82, "english": 76},
{"name": "Charlie", "math": 85, "science": 90, "english": 88}
].
Display "โโโ Report Card โโโ".
For each s in students:
Set total to s["math"] plus s["science"] plus s["english"].
Set avg to round(total divided by 3, 1).
Display s["name"] plus ": Total=" plus total plus ", Avg=" plus avg.
End for.
Output:
โโโ Report Card โโโ
๐ Try It Yourself โ Interactive Programs
Definition: Interactive programs are input-based exercises using the Ask statement that allow learners to practice building dynamic, user-driven applications.
Program 1: Student database (input-based).
Set students to {}.
Ask "How many students? " and store in count.
Convert count to a number.
Repeat from 1 to count as i:
Ask "Enter student name: " and store in name.
Ask "Enter marks: " and store in marks.
Convert marks to a number.
Set students[name] to marks.
End repeat.
Display "".
Display "โโโ Student Database โโโ".
For each name, marks in students:
Set status to "Pass" if marks is greater than or equal to 50 otherwise "Fail".
Display " " plus name plus ": " plus marks plus " (" plus status plus ")".
End for.
Sample Run:
How many students? 3
Enter student name: Alice
Enter Alice's marks: 85
Enter student name: Bob
Enter Bob's marks: 42
Enter student name: Charlie
Enter Charlie's marks: 91
โโโ Student Database โโโ
Alice: 85 (Pass)
Bob: 42 (Fail)
Charlie: 91 (Pass)
Program 2: Contact book (input-based).
Set contacts to {}.
Ask "Enter name: " and store in name.
Ask "Enter phone: " and store in phone.
Ask "Enter email: " and store in email.
Set contacts[name] to {"phone": phone, "email": email}.
Display "".
Display "โโโ Contact Saved โโโ".
Display "Name: " plus name.
Display "Phone: " plus contacts[name]["phone"].
Display "Email: " plus contacts[name]["email"].
Sample Run:
Enter name: Jayaram
Enter phone: 9876543210
Enter email: jayaram@email.com
โโโ Contact Saved โโโ
Name: Jayaram
Phone: 9876543210
Email: jayaram@email.com
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Chapter 11: Classes
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
11.1 Object-Oriented Programming Basics
Definition: Object-oriented programming (OOP) is a programming paradigm that organizes code using objects, which combine data and behavior into a single unit.
Explanation: In UNEL, OOP is based on concepts such as classes, objects, encapsulation, inheritance, and abstraction. It helps structure programs around real-world entities, making code more modular, reusable, and easier to manage.
What is OOP?
Definition: Object-Oriented Programming (OOP) organizes code into objects that combine data (attributes) and behavior (methods) into reusable, self-contained units.
Object-Oriented Programming organizes code around "objects" โ bundles of data and behavior. In UNEL, we use Define shape to create classes.
| OOP Concept | UNEL Equivalent |
|---|---|
| Class | Define shape Name ... |
| Object/Instance | new Name with ... |
| Property/Attribute | Fields defined in the shape |
| Method | Define method name: |
| Constructor | Field initialization with new ... with ... |
| Inheritance | extends ParentName |
11.2 Classes and Instances
Definition: A class is a blueprint that defines the structure and behavior of objects, while an instance is a specific object created from that class.
Explanation: In UNEL, a class describes attributes and methods, and each instance represents a unique realization of that class with its own data. Multiple instances can be created from the same class, each maintaining its own state.
Defining a Shape (Class)
Definition: Defining a shape (class) uses the Define shape statement to create a blueprint with named properties and their data types.
Define shape Student with Name as text, Age as integer, Grade as text.
Note: Create instances.
Set alice to new Student with Name "Alice", Age 20, Grade "A".
Set bob to new Student with Name "Bob", Age 21, Grade "B".
Display alice.Name plus " is " plus alice.Age plus " years old, Grade: " plus alice.Grade.
Display bob.Name plus " is " plus bob.Age plus " years old, Grade: " plus bob.Grade.
Output:
Alice is 20 years old, Grade: A
Bob is 21 years old, Grade: B
Modifying Properties
Definition: Modifying properties changes the attribute values of an existing object instance using dot notation assignment.
Define shape Student with Name as text, Age as integer, Grade as text.
Set bob to new Student with Name "Bob", Age 21, Grade "B".
Display "Before: " plus bob.Grade.
Set bob.Grade to "A".
Display "After: " plus bob.Grade.
Output:
Before: B
After: A
11.3 Instance Methods
Definition: Instance methods are functions defined within a class that operate on a specific instance of that class.
Explanation: In UNEL, instance methods can access and modify the data (attributes) of the object they belong to. They define the behavior of an object and are called using a particular instance, allowing each object to perform actions based on its own state.
Adding Behavior to a Shape
Definition: Adding behavior defines methods within a shape using Define method, giving objects the ability to perform actions based on their data.
Define shape BankAccount with Owner as text, Balance as decimal default 0:
Define method deposit that takes amount:
Set self.Balance to self.Balance plus amount.
Display self.Owner plus " deposited โน" plus amount plus ". Balance: โน" plus self.Balance.
End method.
Define method withdraw that takes amount:
If amount is greater than self.Balance:
Display "Insufficient funds!".
Otherwise:
Set self.Balance to self.Balance minus amount.
Display self.Owner plus " withdrew โน" plus amount plus ". Balance: โน" plus self.Balance.
End if.
End method.
Define method show_balance:
Display self.Owner plus "'s balance: โน" plus self.Balance.
End method.
End shape.
Set account to new BankAccount with Owner "Jayaram", Balance 5000.
account.show_balance().
account.deposit(2000).
account.withdraw(1500).
account.show_balance().
Output:
Jayaram's balance: โน5000
Jayaram deposited โน2000. Balance: โน7000
Jayaram withdrew โน1500. Balance: โน5500
Jayaram's balance: โน5500
11.4 Overloading Operators
Definition: Operator overloading is the ability to define custom behavior for standard operators when they are used with user-defined objects.
Explanation: In UNEL, operator overloading allows classes to specify how operations like addition, subtraction, or comparison should work for their instances. This enables objects to behave naturally with operators, improving readability and expressiveness of code.
Custom Methods Acting as Operators
Definition: Custom operator methods define how standard operations like addition, subtraction, and comparison behave when used with user-defined objects.
Define shape Vector with X as decimal, Y as decimal:
Define method add_vector that takes other:
Return new Vector with X (self.X plus other.X), Y (self.Y plus other.Y).
End method.
Define method magnitude:
Return sqrt(self.X multiplied by self.X plus self.Y multiplied by self.Y).
End method.
Define method to_string:
Return "(" plus self.X plus ", " plus self.Y plus ")".
End method.
End shape.
Set v1 to new Vector with X 3, Y 4.
Set v2 to new Vector with X 1, Y 2.
Set v3 to v1.add_vector(v2).
Display "v1 = " plus v1.to_string().
Display "v2 = " plus v2.to_string().
Display "v1 + v2 = " plus v3.to_string().
Display "|v1| = " plus v1.magnitude().
Output:
v1 = (3, 4)
v2 = (1, 2)
v1 + v2 = (4, 6)
|v1| = 5.0
11.5 Using Modules with Classes
Definition: Using modules with classes refers to importing modules to access and utilize class definitions and related functionality within a program.
Explanation: In UNEL, modules can contain class definitions, and importing them allows reuse of pre-defined classes across different programs. This promotes modular design, code reuse, and better organization by separating class implementations into dedicated modules.
Import Math.
Define shape Circle with Radius as decimal:
Define method area:
Return Math.PI multiplied by self.Radius multiplied by self.Radius.
End method.
Define method circumference:
Return 2 multiplied by Math.PI multiplied by self.Radius.
End method.
Define method describe:
Display "Circle with radius " plus self.Radius.
Display " Area: " plus round(self.area(), 2).
Display " Circumference: " plus round(self.circumference(), 2).
End method.
End shape.
Set my_circle to new Circle with Radius 7.
my_circle.describe().
Output:
Circle with radius 7
Area: 153.94
Circumference: 43.98
๐ Try It Yourself โ Interactive Programs
Definition: Interactive programs are input-based exercises using the Ask statement that allow learners to practice building dynamic, user-driven applications.
Program 1: Bank account simulator (input-based).
Define shape BankAccount with Owner as text, Balance as decimal default 0:
Define method deposit that takes amount:
Set self.Balance to self.Balance plus amount.
Display self.Owner plus " deposited โน" plus amount plus ". Balance: โน" plus self.Balance.
End method.
Define method withdraw that takes amount:
If amount is greater than self.Balance:
Display "Insufficient funds! Balance: โน" plus self.Balance.
Otherwise:
Set self.Balance to self.Balance minus amount.
Display self.Owner plus " withdrew โน" plus amount plus ". Balance: โน" plus self.Balance.
End if.
End method.
Define method show_balance:
Display self.Owner plus "'s balance: โน" plus self.Balance.
End method.
End shape.
Ask "Enter your name: " and store in name.
Ask "Enter initial deposit: " and store in initial.
Convert initial to a number.
Set account to new BankAccount with Owner name, Balance initial.
account.show_balance().
Ask "Enter amount to deposit: " and store in dep.
Convert dep to a number.
account.deposit(dep).
Ask "Enter amount to withdraw: " and store in wd.
Convert wd to a number.
account.withdraw(wd).
account.show_balance().
Sample Run:
Enter your name: Jayaram
Enter initial deposit: 5000
Jayaram's balance: โน5000
Enter amount to deposit: 3000
Jayaram deposited โน3000. Balance: โน8000
Enter amount to withdraw: 2500
Jayaram withdrew โน2500. Balance: โน5500
Jayaram's balance: โน5500
Program 2: Student report card (input-based).
Define shape Student with Name as text, Marks as list:
Define method total:
Set sum to 0.
For each m in self.Marks:
Set sum to sum plus m.
End for.
Return sum.
End method.
Define method average:
Return round(self.total() divided by length(self.Marks), 1).
End method.
Define method grade:
Set avg to self.average().
If avg is greater than or equal to 90:
Return "A+".
Otherwise if avg is greater than or equal to 80:
Return "A".
Otherwise if avg is greater than or equal to 70:
Return "B".
Otherwise if avg is greater than or equal to 60:
Return "C".
Otherwise:
Return "F".
End if.
End method.
End shape.
Ask "Enter student name: " and store in name.
Set scores to [].
Repeat from 1 to 3 as i:
Ask "Enter marks: " and store in m.
Convert m to a number.
Add m to scores.
End repeat.
Set student to new Student with Name name, Marks scores.
Display "".
Display "โโโ Report Card โโโ".
Display "Student: " plus student.Name.
Display "Marks: " plus student.Marks.
Display "Total: " plus student.total().
Display "Average: " plus student.average().
Display "Grade: " plus student.grade().
Sample Run:
Enter student name: Alice
Enter marks for subject 1: 85
Enter marks for subject 2: 92
Enter marks for subject 3: 78
โโโ Report Card โโโ
Student: Alice
Marks: [85, 92, 78]
Total: 255
Average: 85.0
Grade: A
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Chapter 12: Recursion
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Definition: Recursion is a programming technique where a function calls itself to solve a problem by breaking it down into smaller subproblems.
Explanation: In UNEL, a recursive function continues to call itself until a base condition is met. It is commonly used for problems like factorials, Fibonacci sequences, and tree traversal.
12.1 Recursion Basics
Definition: Recursion is a programming technique where a function calls itself to solve a problem by breaking it down into smaller subproblems.
Explanation: In UNEL, a recursive function continues to call itself until a base condition is met, at which point the recursion stops. It is commonly used for problems that can be defined in terms of smaller, similar subproblems, such as factorials or tree traversal.
What is Recursion?
Definition: Recursion is a technique where a function calls itself to solve smaller instances of the same problem until reaching a base case that stops the recursion.
Recursion is when a function calls itself. Every recursive function needs: 1. Base case โ when to stop 2. Recursive case โ calling itself with a simpler problem
Define function countdown that takes n:
If n is less than or equal to 0:
Display "Go!".
Return nothing. Note: Base case โ stop here.
End if.
Display n.
countdown(n minus 1). Note: Recursive case.
End function.
countdown(5).
Output: 5 4 3 2 1 Go!
12.2 Simple Math Recursion
Definition: Simple math recursion applies recursive techniques to fundamental mathematical operations like factorials, exponentiation, and sequence generation.
Factorial
Definition: The factorial function multiplies a number by all positive integers below it (n! = n ร (n-1) ร ... ร 1), with the base case factorial(0) = 1.
Define function factorial that takes n:
If n is less than or equal to 1:
Return 1.
End if.
Return n multiplied by factorial(n minus 1).
End function.
Repeat from 1 to 10 as i:
Display i plus "! = " plus factorial(i).
End repeat.
Power Function
Definition: The recursive power function computes base^exponent by multiplying the base by the result of base^(exponent-1) until the exponent reaches 0.
Define function power_recursive that takes base and exp:
If exp is equal to 0:
Return 1.
End if.
Return base multiplied by power_recursive(base, exp minus 1).
End function.
Display "2^10 = " plus power_recursive(2, 10). Note: 1024
Output:
1024
Fibonacci
Definition: The Fibonacci sequence generates each number as the sum of the two preceding numbers (0, 1, 1, 2, 3, 5, 8...), with base cases fib(0)=0 and fib(1)=1.
Define function fib that takes n:
If n is less than or equal to 0:
Return 0.
End if.
If n is equal to 1:
Return 1.
End if.
Return fib(n minus 1) plus fib(n minus 2).
End function.
Repeat from 0 to 12 as i:
Display "fib(" plus i plus ") = " plus fib(i).
End repeat.
12.3 Recursion with Strings and Lists
Definition: Recursion with strings and lists is the application of recursive functions to process and manipulate sequences of characters or collections of elements.
Explanation: In UNEL, recursive functions handle strings and lists by operating on a smaller portion of the data in each call, such as removing the first element and processing the rest. This continues until a base condition is reached, making it useful for tasks like searching, reversing, or aggregating data.
Reverse a String
Definition: Recursively reversing a string takes the last character and prepends it to the reverse of the remaining string, building the result from end to start.
Define function reverse_string that takes word:
If length(word) is less than or equal to 1:
Return word.
End if.
Return reverse_string(substring(word, 2)) plus char_at(word, 1).
End function.
Display reverse_string("UNEL").
Display reverse_string("Hello").
Output:
LENU
olleH
Sum of a List
Definition: Recursively summing a list adds the first element to the sum of the remaining elements, reducing the list by one element each call.
Define function list_sum that takes items:
If length(items) is equal to 0:
Return 0.
End if.
Return items[1] plus list_sum(drop(items, 1)).
End function.
Display "Sum: " plus list_sum([1, 2, 3, 4, 5]). Note: 15
Output:
15
Check Palindrome
Definition: A recursive palindrome check compares the first and last characters, then recursively checks the inner substring until the string is too short to compare.
Define function is_palindrome that takes word:
If length(word) is less than or equal to 1:
Return true.
End if.
If char_at(word, 1) is not equal to char_at(word, length(word)):
Return false.
End if.
Return is_palindrome(substring(word, 2, length(word) minus 1)).
End function.
Display "madam: " plus is_palindrome("madam").
Display "hello: " plus is_palindrome("hello").
Output:
true
false
12.4 More Math Recursion
Definition: More math recursion extends recursive techniques to advanced algorithms like the Euclidean GCD algorithm and digit sum calculations.
GCD (Euclidean Algorithm)
Definition: The Euclidean algorithm finds the Greatest Common Divisor by repeatedly replacing the larger number with the remainder of the division until the remainder is zero.
Define function gcd_recursive that takes a and b:
If b is equal to 0:
Return a.
End if.
Return gcd_recursive(b, mod(a, b)).
End function.
Display "GCD(48, 18) = " plus gcd_recursive(48, 18). Note: 6
Display "GCD(100, 75) = " plus gcd_recursive(100, 75). Note: 25
Output:
6
25
Sum of Digits
Definition: The sum of digits function recursively extracts each digit using modulo and integer division, adding them together until no digits remain.
Define function digit_sum_recursive that takes n:
If n is less than 10:
Return n.
End if.
Return mod(n, 10) plus digit_sum_recursive(floor(n divided by 10)).
End function.
Display "Sum of digits of 12345: " plus digit_sum_recursive(12345). Note: 15
Output:
15
12.5 Using Recursion to Solve Problems
Definition: Problem-solving recursion applies recursive thinking to classic algorithms like Tower of Hanoi and binary search.
Tower of Hanoi
Definition: The Tower of Hanoi is a classic recursive puzzle where disks are moved between three pegs following size constraints, solved by recursive decomposition.
Define function hanoi that takes n and source and target and auxiliary:
If n is equal to 1:
Display "Move disk 1 from " plus source plus " to " plus target.
Return nothing.
End if.
hanoi(n minus 1, source, auxiliary, target).
Display "Move disk " plus n plus " from " plus source plus " to " plus target.
hanoi(n minus 1, auxiliary, target, source).
End function.
Display "โโโ Tower of Hanoi (3 disks) โโโ".
hanoi(3, "A", "C", "B").
Output:
โโโ Tower of Hanoi (3 disks) โโโ
Binary Search (Recursive)
Definition: Recursive binary search repeatedly divides a sorted list in half, comparing the target with the middle element to narrow the search space logarithmically.
Define function binary_search that takes arr and target and low and high:
If low is greater than high:
Return -1.
End if.
Set mid to floor((low plus high) divided by 2).
If arr[mid] is equal to target:
Return mid.
Otherwise if arr[mid] is less than target:
Return binary_search(arr, target, mid plus 1, high).
Otherwise:
Return binary_search(arr, target, low, mid minus 1).
End if.
End function.
Set data to [2, 5, 8, 12, 16, 23, 38, 56, 72, 91].
Set pos to binary_search(data, 23, 1, length(data)).
Display "Found 23 at position: " plus pos.
๐ Try It Yourself โ Interactive Programs
Definition: Interactive programs are input-based exercises using the Ask statement that allow learners to practice building dynamic, user-driven applications.
Program 1: Factorial calculator (input-based).
Define function factorial that takes n:
If n is less than or equal to 1:
Return 1.
End if.
Return n multiplied by factorial(n minus 1).
End function.
Ask "Enter a number: " and store in num.
Convert num to a number.
Display num plus "! = " plus factorial(num).
Sample Run:
Enter a number: 6
6! = 720
Program 2: Palindrome checker (input-based).
Define function is_palindrome that takes str:
Set reversed to reverse(lowercase(str)).
Return lowercase(str) is equal to reversed.
End function.
Ask "Enter a word: " and store in word.
Display "".
If is_palindrome(word):
Display "'" plus word plus "' is a palindrome! โ
".
Otherwise:
Display "'" plus word plus "' is NOT a palindrome. โ".
End if.
Sample Run:
Enter a word: madam
'madam' is a palindrome! โ
Program 3: Power calculator using recursion (input-based).
Define function power_recursive that takes base and exp:
If exp is equal to 0:
Return 1.
End if.
Return base multiplied by power_recursive(base, exp minus 1).
End function.
Ask "Enter base: " and store in base.
Ask "Enter exponent: " and store in exp.
Convert base to a number.
Convert exp to a number.
Display base plus "^" plus exp plus " = " plus power_recursive(base, exp).
Sample Run:
Enter base: 2
Enter exponent: 10
2^10 = 1024
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Chapter 13: Inheritance
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Definition: Inheritance is an object-oriented concept where one class derives properties and behavior from another class.
Explanation: In UNEL, a derived (child) class can reuse and extend the attributes and methods of a base (parent) class. This promotes code reuse and allows hierarchical relationships between classes.
13.1 Inheritance Basics
Definition: Inheritance is an object-oriented concept where one class derives properties and behavior from another class.
Explanation: In UNEL, a derived (child) class can reuse and extend the attributes and methods of a base (parent) class. This promotes code reuse, reduces duplication, and allows hierarchical relationships between classes.
What is Inheritance?
Definition: Inheritance allows a child class to acquire all properties and methods from a parent class, extending or specializing its behavior.
Inheritance lets you create a new class based on an existing one. The new class inherits all fields and methods from the parent.
Define shape Animal with Name as text, Sound as text:
Define method speak:
Display self.Name plus " says " plus self.Sound plus "!".
End method.
End shape.
Define shape Dog extends Animal with Breed as text.
Set buddy to new Dog with Name "Buddy", Sound "Woof", Breed "Labrador".
buddy.speak().
Display "Breed: " plus buddy.Breed.
Output:
Buddy says Woof!
Breed: Labrador
13.2 Attribute Access
Definition: Attribute access is the process of retrieving or modifying the properties (attributes) of an object.
Explanation: In UNEL, attributes are accessed using the object followed by the attribute name. This allows reading or updating the state of an object and is fundamental to interacting with object data in object-oriented programming.
Inherited Attributes
Definition: Inherited attributes are properties defined in a parent class that are automatically available in all child classes without redeclaration.
A child shape has all the attributes of the parent, plus its own:
Define shape Vehicle with Make as text, Model as text, Year as integer.
Define shape Car extends Vehicle with Doors as integer default 4.
Define shape Motorcycle extends Vehicle with HasSidecar as boolean default false.
Set car to new Car with Make "Toyota", Model "Camry", Year 2024, Doors 4.
Set bike to new Motorcycle with Make "Harley", Model "Street", Year 2023.
Display car.Make plus " " plus car.Model plus " (" plus car.Year plus ") โ " plus car.Doors plus " doors".
Display bike.Make plus " " plus bike.Model plus " (" plus bike.Year plus ") โ Sidecar: " plus bike.HasSidecar.
Output:
Toyota Camry (2024) โ 4 doors
Harley Street (2023) โ Sidecar: false
13.3 Methods
Definition: Methods are functions that are defined within a class and are associated with objects of that class.
Explanation: In UNEL, methods define the behavior of objects and can access and modify their attributes. They are called on instances of a class, enabling objects to perform specific actions based on their state.
Overriding Methods
Definition: Method overriding allows a child class to provide its own implementation of a method defined in the parent class, customizing inherited behavior.
A child class can provide its own version of a parent's method:
Define shape BaseShape with Name as text:
Define method describe:
Display "I am a " plus self.Name plus ".".
End method.
End shape.
Define shape Circle extends BaseShape with Radius as decimal:
Define method describe:
Display "I am a circle with radius " plus self.Radius plus ".".
End method.
Define method area:
Return 3.14159 multiplied by self.Radius multiplied by self.Radius.
End method.
End shape.
Define shape Rectangle extends BaseShape with Width as decimal, Height as decimal:
Define method describe:
Display "I am a " plus self.Width plus "ร" plus self.Height plus " rectangle.".
End method.
Define method area:
Return self.Width multiplied by self.Height.
End method.
End shape.
Set my_circle to new Circle with Name "Circle", Radius 5.
Set my_rectangle to new Rectangle with Name "Rectangle", Width 10, Height 6.
my_circle.describe().
Display "Area: " plus round(my_circle.area(), 2).
my_rectangle.describe().
Display "Area: " plus my_rectangle.area().
Output:
I am a circle with radius 5.
Area: 78.54
I am a 10ร6 rectangle.
Area: 60
13.4 Hierarchical Inheritance
Definition: Hierarchical inheritance is a type of inheritance where multiple child classes inherit from a single parent class.
Explanation: In UNEL, a base class provides common attributes and methods, while multiple derived classes extend or specialize this behavior. This allows shared functionality to be reused across different classes while enabling each child class to have its own unique features.
Define shape Employee with Name as text, Salary as decimal:
Define method info:
Display self.Name plus " โ Salary: โน" plus self.Salary.
End method.
End shape.
Define shape Manager extends Employee with Department as text:
Define method info:
Display self.Name plus " โ Manager of " plus self.Department plus " โ โน" plus self.Salary.
End method.
End shape.
Define shape Developer extends Employee with Language as text:
Define method info:
Display self.Name plus " โ " plus self.Language plus " Developer โ โน" plus self.Salary.
End method.
End shape.
Set mgr to new Manager with Name "Alice", Salary 120000, Department "Engineering".
Set dev to new Developer with Name "Bob", Salary 80000, Language "UNEL".
mgr.info().
dev.info().
Output:
Alice โ Manager of Engineering โ โน120000
Bob โ UNEL Developer โ โน80000
13.5 Multiple Inheritance and Interfaces
Definition: Multiple inheritance is a type of inheritance where a class derives properties and behavior from more than one parent class.
Explanation: In UNEL, a child class can inherit attributes and methods from multiple base classes, allowing it to combine functionalities from different sources. This provides flexibility but requires careful design to avoid conflicts between inherited members.
Interfaces
Definition: Interfaces define a contract of methods that implementing classes must provide, ensuring consistent behavior across different class hierarchies.
Define interface Drawable:
Requires method draw.
End interface.
Define interface Resizable:
Requires method resize.
End interface.
Define shape Widget implements Drawable with Label as text:
Define method draw:
Display "Drawing widget: " plus self.Label.
End method.
End shape.
Set btn to new Widget with Label "Submit Button".
btn.draw().
Output:
Drawing widget: Submit Button
๐ Try It Yourself โ Interactive Programs
Definition: Interactive programs are input-based exercises using the Ask statement that allow learners to practice building dynamic, user-driven applications.
Program 1: Shape calculator with inheritance (input-based).
Define shape BaseShape with Name as text:
Define method describe:
Display "I am a " plus self.Name plus ".".
End method.
End shape.
Define shape Circle extends BaseShape with Radius as decimal:
Define method area:
Return round(3.14159 multiplied by self.Radius multiplied by self.Radius, 2).
End method.
End shape.
Define shape Rectangle extends BaseShape with Width as decimal, Height as decimal:
Define method area:
Return self.Width multiplied by self.Height.
End method.
End shape.
Ask "Choose shape (1=Circle, 2=Rectangle): " and store in choice.
Convert choice to a number.
If choice is equal to 1:
Ask "Enter radius: " and store in r.
Convert r to a number.
Set chosen to new Circle with Name "Circle", Radius r.
chosen.describe().
Display "Area: " plus chosen.area().
Otherwise:
Ask "Enter width: " and store in w.
Ask "Enter height: " and store in h.
Convert w to a number.
Convert h to a number.
Set chosen to new Rectangle with Name "Rectangle", Width w, Height h.
chosen.describe().
Display "Area: " plus chosen.area().
End if.
Sample Run:
Choose shape (1=Circle, 2=Rectangle): 1
Enter radius: 5
I am a Circle.
Area: 78.54
Program 2: Employee system with inheritance (input-based).
Define shape Employee with Name as text, Salary as decimal:
Define method info:
Display self.Name plus " โ โน" plus self.Salary.
End method.
End shape.
Define shape Manager extends Employee with Department as text:
Define method info:
Display self.Name plus " โ Manager of " plus self.Department plus " โ โน" plus self.Salary.
End method.
End shape.
Ask "Enter employee name: " and store in name.
Ask "Enter salary: " and store in salary.
Convert salary to a number.
Ask "Enter department: " and store in dept.
Set mgr to new Manager with Name name, Salary salary, Department dept.
mgr.info().
Sample Run:
Enter employee name: Jayaram
Enter salary: 85000
Enter department: Engineering
Jayaram โ Manager of Engineering โ โน85000
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Chapter 14: Files and Exceptions
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Definition: Files and exceptions refer to handling external file operations and managing runtime errors within a program.
Explanation: In UNEL, file operations allow reading from and writing to files for data storage and retrieval, while exceptions handle unexpected errors during execution. Using structured error handling ensures programs remain stable and can respond gracefully to failures.
14.1 Reading from Files
Definition: File reading is the process of accessing and retrieving data from a file stored on a system.
Explanation: In UNEL, file reading allows programs to load external data for processing. It involves opening a file, reading its contents, and handling the data appropriately, often with error handling to manage issues like missing files or invalid formats.
Reading an Entire File
Definition: Reading an entire file loads all contents into memory as a single string using the file_read() function.
Note: FILE I/O โ requires VM mode.
Set content to file_read("data.txt").
Display "File contents:".
Display content.
Output:
File contents:
Reading Lines
Definition: Reading lines loads a file and splits its contents into a list of individual lines for line-by-line processing.
Note: FILE I/O โ requires VM mode.
Set content to file_read("students.txt").
Set lines to split_lines(content).
For each line in lines:
Display ">> " plus line.
End for.
Checking if a File Exists
Definition: The file_exists() function tests whether a file is present at a specified path, returning true or false to prevent errors when reading.
If file_exists("config.txt"):
Set config to file_read("config.txt").
Display "Config loaded.".
Otherwise:
Display "Config file not found, using defaults.".
End if.
Output:
Config loaded.
Config file not found, using defaults.
14.2 Writing to Files
Definition: File writing is the process of creating or modifying a file by storing data into it.
Explanation: In UNEL, file writing allows programs to save information for later use. It involves opening a file in write mode, adding content, and ensuring proper handling of errors to maintain data integrity.
Writing Text to a File
Definition: The file_write() function creates or overwrites a file with specified text content, saving data to persistent storage.
Note: FILE I/O โ requires VM mode.
Set data to "Name,Age,City\nAlice,25,Mumbai\nBob,30,Delhi\nCharlie,22,Bangalore".
file_write("output.csv", data).
Display "File written successfully.".
Output:
File written successfully.
Writing Program Output
Definition: Writing program output saves computed results to a file, creating a permanent record of the program's work.
Note: FILE I/O โ requires VM mode.
Set report to "".
Set report to report plus "โโโ Student Report โโโ\n".
Set report to report plus "Alice: 92\n".
Set report to report plus "Bob: 78\n".
Set report to report plus "Charlie: 85\n".
file_write("report.txt", report).
Display "Report saved to report.txt.".
Output:
Report saved to report.txt.
14.3 Handling Exceptions
Definition: Exception handling is the process of detecting and managing runtime errors to prevent program crashes and ensure smooth execution.
Explanation: In UNEL, exception handling is performed using constructs like Try and Catch, allowing programs to handle errors gracefully, provide meaningful messages, and continue execution when possible.
Try-Catch for Error Handling
Definition: Try-Catch wraps code that might fail in a Try block, with a Catch block that handles any errors and prevents program crashes.
Try:
Set result to 10 divided by 0.
Catch error:
Display "Error caught: " plus error.
End try.
Display "Program continues after the error.".
Output:
Program continues after the error.
Catching File Errors
Definition: Catching file errors uses Try-Catch around file operations to gracefully handle missing files, permission issues, or corrupt data.
Try:
Set content to file_read("nonexistent.txt").
Display content.
Catch error:
Display "Could not read file: " plus error.
End try.
Catching Conversion Errors
Definition: Catching conversion errors handles failures when converting invalid text to numbers, such as attempting to convert 'abc' to a number.
Try:
Set result to to_integer("not_a_number").
Catch error:
Display "Conversion failed: " plus error.
End try.
14.4 Raising Exceptions
Definition: Raising exceptions is the act of explicitly generating an error within a program to signal that an abnormal or invalid condition has occurred.
Explanation: In UNEL, raising an exception allows a program to stop normal execution and transfer control to an error-handling mechanism. It is used to enforce rules, validate input, and handle unexpected situations in a controlled manner.
Throwing Custom Errors
Definition: The Throw statement explicitly raises a custom error with a descriptive message, signaling that an invalid condition has been detected.
Define function validate_score that takes score:
If score is less than 0:
Throw "Score cannot be negative: " plus score.
End if.
If score is greater than 100:
Throw "Score cannot exceed 100: " plus score.
End if.
Return score.
End function.
Try:
Display validate_score(85). Note: OK
Display validate_score(150). Note: Throws error
Catch error:
Display "Validation error: " plus error.
End try.
Output:
OK
Throws error
Assert Statements
Definition: Assert statements verify that a condition is true and raise an error with a message if it is false, used for debugging and validation.
Set age to 25.
Assert age is greater than 0, "Age must be positive.".
Assert age is less than 150, "Age must be realistic.".
Display "Age is valid: " plus age.
๐ Try It Yourself โ Interactive Programs
Definition: Interactive programs are input-based exercises using the Ask statement that allow learners to practice building dynamic, user-driven applications.
Program 1: Safe division with error handling (input-based).
Ask "Enter a number: " and store in a.
Ask "Enter divisor: " and store in b.
Try:
Convert a to a number.
Convert b to a number.
If b is equal to 0:
Throw "Cannot divide by zero!".
End if.
Set result to a divided by b.
Display a plus " รท " plus b plus " = " plus result.
Catch error:
Display "โ Error: " plus error.
End try.
Display "Program finished successfully.".
Sample Run (valid):
Enter a number: 100
Enter divisor: 4
100 รท 4 = 25
Program finished successfully.
Sample Run (error):
Enter a number: 100
Enter divisor: 0
โ Error: Cannot divide by zero!
Program finished successfully.
Program 2: Age validator with custom exceptions (input-based).
Define function validate_age that takes age:
If age is less than 0:
Throw "Age cannot be negative: " plus age.
End if.
If age is greater than 150:
Throw "Age is unrealistic: " plus age.
End if.
Return age.
End function.
Ask "Enter your age: " and store in input_age.
Try:
Convert input_age to a number.
Set valid_age to validate_age(input_age).
Display "".
Display "โ
Valid age: " plus valid_age.
If valid_age is greater than or equal to 18:
Display "You are eligible to vote.".
Otherwise:
Display "You are not eligible to vote yet.".
End if.
Catch error:
Display "".
Display "โ Validation error: " plus error.
End try.
Sample Run:
Enter your age: 21
โ
Valid age: 21
You are eligible to vote.
Program 3: File-based note taker (input-based).
Ask "Enter a note: " and store in note.
Try:
file_write("my_notes.txt", note).
Display "โ
Note saved to my_notes.txt.".
Set content to file_read("my_notes.txt").
Display "".
Display "โโโ Saved Note โโโ".
Display content.
Catch error:
Display "โ Could not save: " plus error.
End try.
Sample Run:
Enter a note: Remember to study UNEL Chapter 14!
โ
Note saved to my_notes.txt.
โโโ Saved Note โโโ
Remember to study UNEL Chapter 14!
Chapter 15: Libraries
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Definition: Libraries are collections of pre-written modules, functions, and classes that provide reusable functionality for programs.
Explanation: In UNEL, libraries extend the capabilities of the language by offering ready-made solutions for common tasks such as mathematics, text processing, and data handling. They promote code reuse, efficiency, and faster development.
15.1 Built-in Functions โ Complete Reference
Definition: Built-in functions are predefined functions that are available for use without requiring any import.
Explanation: In UNEL, built-in functions provide commonly used operations such as mathematical calculations, string manipulation, list processing, and type conversion. They simplify programming by offering ready-to-use functionality.
Type Functions
Definition: Type functions perform data type inspection and conversion, including type_of(), to_number(), to_text(), and to_decimal().
Display typeof(42). Note: integer
Display typeof(3.14). Note: decimal
Display typeof("Hello"). Note: text
Display typeof(true). Note: boolean
Display typeof([1, 2]). Note: list
Display typeof(nothing). Note: nothing
Display to_integer("42"). Note: 42
Display to_decimal("3.14"). Note: 3.14
Display to_text(42). Note: "42"
Display to_boolean(1). Note: true
Output:
integer
decimal
text
boolean
list
nothing
42
3.14
"42"
true
Math Functions
Definition: Math functions provide numerical operations including abs(), round(), floor(), ceil(), power(), sqrt(), min(), max(), and random number generation.
Display abs(-7). Note: 7
Display sqrt(144). Note: 12
Display power(2, 10). Note: 1024
Display round(3.14159, 2). Note: 3.14
Display floor(3.9). Note: 3
Display ceil(3.1). Note: 4
Display mod(17, 5). Note: 2
Display min(3, 7). Note: 3
Display max(3, 7). Note: 7
Display factorial(5). Note: 120
Display gcd(12, 8). Note: 4
Display lcm(4, 6). Note: 12
Display is_prime(17). Note: true
Display sign(-5). Note: -1
Display clamp(15, 0, 10). Note: 10
Display digits(123). Note: [1, 2, 3]
Display digit_sum(123). Note: 6
Output:
7
12
1024
3.14
3
4
2
3
7
120
4
12
true
-1
10
[1, 2, 3]
6
String Functions
Definition: String functions provide text manipulation operations including length(), uppercase(), lowercase(), trim(), contains(), split(), join(), and many more.
Set greeting to "Hello, World!".
Display length(greeting). Note: 13
Display uppercase(greeting). Note: HELLO, WORLD!
Display lowercase(greeting). Note: hello, world!
Display capitalize("hello"). Note: Hello
Display trim(" hi "). Note: hi
Display contains(greeting, "World"). Note: true
Display starts_with(greeting, "Hello"). Note: true
Display ends_with(greeting, "!"). Note: true
Display replace(greeting, "World", "UNEL"). Note: Hello, UNEL!
Display split("a,b,c", ","). Note: ["a", "b", "c"]
Display join(["a","b","c"], "-"). Note: a-b-c
Display index_of(greeting, "World"). Note: 8
Display char_at(greeting, 1). Note: H
Display reverse(greeting). Note: !dlroW ,olleH
Display repeat_string("ab", 3). Note: ababab
Display word_count("Hello World"). Note: 2
Display words("Hello World"). Note: ["Hello", "World"]
Display pad_left("5", 3, "0"). Note: 005
Display pad_right("hi", 5, "."). Note: hi...
Display count_char("hello", "l"). Note: 2
Display remove_char("hello", "l"). Note: heo
Display center("Hi", 10, "-"). Note: ----Hi----
Output:
13
HELLO, WORLD!
hello, world!
Hello
hi
true
true
true
Hello, UNEL!
["a", "b", "c"]
a-b-c
8
H
!dlroW ,olleH
ababab
2
["Hello", "World"]
005
hi...
2
heo
----Hi----
List Functions
Definition: List functions provide collection operations including Add, Remove, sort(), reverse(), contains(), index_of(), slice(), flatten(), and unique().
Set nums to [5, 3, 8, 1, 9].
Display length(nums). Note: 5
Display sort(nums). Note: [1, 3, 5, 8, 9]
Display reverse(nums). Note: [9, 1, 8, 3, 5]
Display contains(nums, 8). Note: true
Display index_of(nums, 8). Note: 3
Display unique([1,1,2,3,3]). Note: [1, 2, 3]
Display flatten([[1,2],[3,4]]). Note: [1, 2, 3, 4]
Display sum(nums). Note: 26
Display average(nums). Note: 5.2
Display min(nums). Note: 1
Display max(nums). Note: 9
Display take(nums, 3). Note: [5, 3, 8]
Display drop(nums, 2). Note: [8, 1, 9]
Display chunk([1,2,3,4,5,6], 2). Note: [[1,2],[3,4],[5,6]]
Display zip([1,2], ["a","b"]). Note: [[1,"a"],[2,"b"]]
Display enumerate(["a","b"]). Note: [[1,"a"],[2,"b"]]
Display range(1, 5). Note: [1, 2, 3, 4, 5]
Display frequencies([1,1,2,3,3]). Note: {"1":2,"2":1,"3":2}
Output:
5
[1, 3, 5, 8, 9]
[9, 1, 8, 3, 5]
true
3
[1, 2, 3]
[1, 2, 3, 4]
26
5.2
1
9
[5, 3, 8]
[8, 1, 9]
[[1,2],[3,4],[5,6]]
[[1,"a"],[2,"b"]]
[[1,"a"],[2,"b"]]
[1, 2, 3, 4, 5]
{"1":2,"2":1,"3":2}
Higher-Order Functions
Definition: Higher-order list functions include map(), filter(), and reduce() which apply transformations, selections, and aggregations to list data.
Set ns to [1, 2, 3, 4, 5].
Display map(ns, lambda x: x multiplied by 2). Note: [2,4,6,8,10]
Display filter(ns, lambda x: x is greater than 3). Note: [4, 5]
Display reduce(ns, lambda a, x: a plus x, 0). Note: 15
Display every(ns, lambda x: x is greater than 0). Note: true
Display some(ns, lambda x: x is greater than 4). Note: true
Display sort_by([{"n":3},{"n":1}], lambda x: x["n"]). Note: [{"n":1},{"n":3}]
Output:
[2,4,6,8,10]
[4, 5]
15
true
true
[{"n":1},{"n":3}]
Dictionary Functions
Definition: Dictionary functions provide key-value operations including keys(), values(), has_key(), remove_key(), merge(), and length().
Set info to {"a": 1, "b": 2, "c": 3}.
Display keys(info). Note: ["a", "b", "c"]
Display values(info). Note: [1, 2, 3]
Display has_key(info, "b"). Note: true
Display length(info). Note: 3
Output:
["a", "b", "c"]
[1, 2, 3]
true
3
Utility Functions
Definition: Utility functions provide general-purpose operations including sleep(), timestamp(), hash(), and range() for various programming needs.
Display uuid_gen(). Note: random UUID
Display hash_text("Hello"). Note: SHA-256 hash
Display to_char_codes("ABC"). Note: [65, 66, 67]
Display from_char_codes([72,105]). Note: Hi
Display deep_copy([1, [2, 3]]). Note: independent copy
Display random(). Note: random 0.0-1.0
Display random(1, 100). Note: random integer 1-100
Output:
random UUID
SHA-256 hash
[65, 66, 67]
Hi
independent copy
random 0.0-1.0
random integer 1-100
Bitwise Functions
Definition: Bitwise functions perform binary-level operations on integers including bit_and(), bit_or(), bit_xor(), bit_not(), and bit shifts.
Display bit_and(12, 10). Note: 8
Display bit_or(12, 10). Note: 14
Display bit_xor(12, 10). Note: 6
Display bit_not(12). Note: -13
Display bit_shift_left(1, 4). Note: 16
Display bit_shift_right(16, 2). Note: 4
Output:
8
14
6
-13
16
4
Date/Time Functions
Definition: Date/time functions provide current date and time retrieval, formatting, and timestamp operations for time-aware applications.
Display now_time(). Note: current date and time
Display year(). Note: current year
Display month(). Note: current month
Display day(). Note: current day
Output:
current date and time
current year
current month
current day
JSON Functions
Definition: JSON functions provide serialization and deserialization of data structures, converting between UNEL objects and JSON text format.
Set data to {"name": "Alice", "age": 25}.
Set json_text to to_json(data).
Display json_text.
Set parsed to parse_json(json_text).
Display parsed["name"].
Regex Functions
Definition: Regex functions provide pattern matching and text searching using regular expressions for advanced string processing.
Set message to "Order 123, Order 456, Order 789".
Display regex_match(message, "\\d+"). Note: true
Display regex_find(message, "\\d+"). Note: ["123","456","789"]
Display regex_replace(message, "\\d+", "XXX"). Note: Order XXX, Order XXX, Order XXX
Display regex_split("a,,b,c", ",+"). Note: ["a","b","c"]
Output:
true
["123","456","789"]
Order XXX, Order XXX, Order XXX
["a","b","c"]
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
APPENDIX: Quick Reference Card
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Note: โโโ UNEL Quick Reference Card โโโ
Note: โโ Output โโ
Display "Hello, World!".
Note: โโ Input โโ
Ask "Your name? " and store in name.
Ask "Your age? " and store in age.
Convert age to a number.
Note: โโ Variables โโ
Set count to 42.
Constant PI is 3.14159.
Increase count by 5.
Decrease count by 2.
Set first to 10.
Set second to 20.
Swap first and second.
Note: โโ Conditionals โโ
Set score to 85.
If score is greater than or equal to 90:
Display "A+".
Otherwise if score is greater than or equal to 80:
Display "A".
Otherwise:
Display "B".
End if.
Note: โโ Loops โโ
Set counter to 3.
While counter is greater than 0:
Display counter.
Decrease counter by 1.
End while.
Repeat 3 times:
Display "UNEL!".
End repeat.
Repeat from 1 to 5 as i:
Display i.
End repeat.
Set colors to ["red", "green", "blue"].
For each color in colors:
Display color.
End for.
Note: โโ Functions โโ
Define function calculate that takes x and y:
Return x plus y.
End function.
Note: โโ Structures โโ
Define shape Person with Name as text, Age as integer:
Define method greet:
Display "Hi, I'm " plus self.Name.
End method.
End shape.
Set person to new Person with Name "Alice", Age 25.
person.greet().
Note: โโ Error Handling โโ
Try:
Set result to 10 divided by 0.
Catch error:
Display error.
End try.
Note: โโ Lists โโ
Set items to [1, 2, 3].
Add 4 to items.
Display items[1].
Display length(items).
Note: โโ Dictionaries โโ
Set data to {"key": "value"}.
Display data["key"].
Set data["new_key"] to "new_value".
Note: โโ Comments โโ
Note: This is a comment.
End of UNEL: The Complete Textbook โ Version 1.0
Programming in Natural English. Syntax IS English Grammar.
ยฉ 2026 K N S Jaya Rami Reddy. All rights reserved.