Learn Programming: Terminal (Console) Output
Image credits: Image created by the author using the program Spectacle.
Requirements
In the introduction to development environments, I have mentioned Python, Lua and JavaScript as good choices of programming languages for beginners. Later, I have commented about GDScript as an option for people who want to program digital games or simulations. For the introductory programming activities, you will need, at least, a development environment configured for one of the previous languages.
If you wish to try programming without configuring an environment, you can use of the online editors that I have created:
However, they do not provide all features offered by interpreters for the languages. Thus, sooner or later, you will need to set up a development environment. If you need to configure one, you can refer to the following resources.
Thus, if you have an Integrated Development Environment (IDE), or a combination of text editor and an interpreter, you are ready to start. The following example assumes that you know how to run code in your chosen language, as presented in the configuration pages.
If you want to use another language, the introduction provides links for configure development environments for the C, C++, Java, LISP, Prolog, and SQL (with SQLite) languages. In many languages, it suffices to follow the models from the experimentation section to modify syntax, commands and functions from the code blocks. C and C++ are exceptions, for they require pointers access the memory.
From the Structure to the Program
In Entry Point and Program Structure, it was commented about basic program structures written in programming languages. Hereafter, you will start to write your own programs.
Programming languages that use source code in the form of text are the most common ones. However, they are not the only ones.
To reinforce that programming languages are tools, before starting programming activities in the traditional way, one can explore a different way to program.
Visual Programming Languages
It is important to recognize programs' structure, though that can be difficult for beginners. The textual representation is abstract, something that can make it harder to visualize the structure.
There exists programming languages are not textual. One of the most popular alternative is the use of visual programming languages.
Visual programming languages commonly use a metaphor of blocks as the basic programming unit. Some benefits of visual programming languages are the possibility to graphically visualize the code, and the abstraction of the syntax using blocks, which makes it easier to create source code without syntax errors. Some disadvantages are the inefficiency to create source code (dragging and dropping blocks is often slower than writing), and the requirement of vision and fine motor skills to program. Thus, visual languages are inherently inaccessible to people with visual disabilities, and they potentially are hard to use by people with motor disabilities.
If you are sighted person, the use of a visual language can be beneficial. A very common difficulty for people starting programming activities is how to think about a program, for, like a significant part of Mathematics, programming is an abstract practice. Visual programming can help you to think in code in a more concrete and less conceptual way. For instance, you can imagine sequences of code as blocks that compose a program. The visual metaphors help to reinforce this kind of visualization.
One of the most popular visual programming language is Scratch, designed especially for children. A similar alternative to Scratch is Blockly. There are also other metaphors, as using flowcharts. Two programs that enable visual programming with flowcharts are RAPTOR and Flowgorithm.
None of the previous four languages are particularly used for software development by professional, though all are interesting optins to stimulate learning.
Nevertheless, this does mean that visual languages cannot be used professionally, on the contrary. For instance, Godot Engine provides VisualScript to create games with the engine. The 3D modeling program Blender provides UPBGE (successor of Blender Game Engine), that is also a visual programming language to create digital games. For modeling for architecture, civil engineering, and industrial design projects, there exists Dynamo. Thus, one should not think of visual programming languages as toys, but as proper programming languages.
Perhaps that Scratch and RAPTOR are the most popular options in their categories. However, Flowgorithm has a better support for non-Windows operating systems (using WINE (Wine Is Not an Emulator)), with version for Android and iOS under development. Moreover, Flowgorithm supports multiple (human) languages, including Portuguese. Thus, Scratch and Flowgorithm will be adopted for some examples, to illustrate program implementation and how they work.
First Program in Flowchart Using Flowgorithm
If you wish to install Flowgorithm, browse to the downloads' page of the project. Choose the version that is compatible with your operating system.
On Windows, chooser one installer to set up the program in your machine.
On macOS and Linux, you must use WINE
to run the program.
After installing and running the program, you can change the language of t he interface in Appearance, then in Change Language....
Alternatively, you can press the F12
shortcut.
A flowchart starts in a command block called Start (Main, in Flowgorithm), and ends in block called End. Intermediate blocks represent the program instructions. In flowcharts, each kind of block has its own shape.
To add an element (a new block) in the flowchart, you should right-click on the existing arrows.
To write a message, choose the Output block.
The box will be gray, suggesting that the element is still incomplete and requiring values (in this case, the message).
To define the text that will be written, double-click on the created outputbox.
Write a message between double quotes (for instance, Hello, my name is Franco!
) and confirm in OK.
The box should become green.
To run the program, use the play (🢒
) icon or press the shortcut F5
.
The output of the program is going to appear in a new window.
The text in the images are from the Portuguese version of this page.
To visualize how the flowchart is interpreted, you can change the play speed of the program in the icon of play above three squares. Choose the slowest speed (Slow) and run the program again.
The boxes will change colors when they are being executed. To ease the visualization, you can add new messages.
Congratulations! Now Flowgorithm is part of your tools for programming, as well as flowcharts.
By the way, observe how the structure of the flowchart resembles an algorithm (as presented in entry point and program structure).
The structure of the resulting flowchart is:
- Begin:
- Output: "Hello, my name is Franco!".
- End.
The structure of an equivalent algorithm is:
begin
write("Olá, meu nome é Franco!")
end
In other words, flowcharts can be used instead of algorithms to describe programs. This shows that it is possible to create programs without a traditional (or visual) programming language. Thus, you can choose for whatever you prefer.
Besides, a benefit of using flowcharts is its potential of visually illustrating the implementation of a program. Observe that the boxes change colors when they are executed. Computers work in the same way, running an instruction at a time.
First Program in a Visual Language Using Scratch
Scratch can be used online in the official page of the project. The website can be translated to Portuguese and other languages. You can change the language in the bottom part of the page.
To create a program in Scratch, search for Start Creating.
To create your first program, you will need two blocks.
For the first, choose the option Events in the side menu. Next, choose the first block: When ⚑ clicked. Click and drag he block to the central panel, then drop it.
Next, choose the option Looks in the side menu. Search for the block say Hello!. Click and drag the it to the central panel. For the block under the first, then drop it.
To change the message, click on Hello!
.
Write something like Hello, my name is Franco!
.
You can change Franco
by your name.
You can also write any other text -- for instance, My first program in Scratch
.
To run your program, click on the icon of the green flag (⚑), that is next to the sign of the stop sign (the red hexagon: ⬣).
If the page is in Portuguese, your program should resemble the one in the following image.
If the page is in English, the names (but not the contents) of blocks will be translated.
Congratulations! Now Scratch is also part of your programming tools.
Optionally, if you want to add an end to your Scratch code, you can use the block stop all in Control. In this case, swap the block to write a message by one that is timed. Otherwise, the message will disappear before you can see it.
Textual Programming Languages
Programming with text is similar to programming with blocks. The difference is that, now, you will have to type text in a text editor instead of dragging and dropping boxes in a window.
Thus, if you would rather keep learning in a visual way, you can. Whenever you wish to switch to textual programming, the acquired knowledge will remain valid. In other words, now you have more options to learn computational thinking. Choose the one you prefer.
In textual programming, it is important to write the reserved words correctly, as well as respect the other required rules to write the source code. Otherwise, the program will not work, due to a syntax error. The visual programming avoids the occurrence of syntactical errors, because the blocks represent the syntax. In textual languages, a typing error can result into a non-working program.
It is time to your development environment!
Development Environment
A minimal development environment requires a program to write text (a text editor), a program to convert the text code into code compatible with the machine (a compiler or a interpreter), and a command line interpreter (shell). There exists programs called IDEs that combine all the previous programs into a single one.
Thus, to program, you will need a text editor or a IDE configured for your chosen language. If you need to configure a development environment, refer to the following resources. My advice is choosing one the recommended IDEs for your language of choice.
Alternatively, you can use one of the following online environments that I have provided:
- JavaScript code editor and interpreter;
- Lua code editor and interpreter;
- Python code editor and interpreter.
This choice can be helpful because you will not have to use a text editor and interpreter, or IDE in your first activities. Once you are ready (or when you find a feature that is not supported by the environment), you can set up your development environment to continue your learning.
Using a Text Editor or a IDE
You can create files and folders (directories) using file managers (such as the File Explorer
on Windows, Dolphin
on KDE or Files
in Gnome on Linux).
The process is described in the previous link.
You can also create files and directories using an IDE or a text editor.
To do this, click on File, then on New (the usual shortcut is Ctrl n
).
With the newly created file, you can type the text with the code.
When you are finished, you should save the file.
Even better, create the habit of saving your file with code frequently, to avoid data loss during power outages or if the text editor (or IDE, or even your operating system) crashes.
To save the file, click on File, then on Save to save in the same file being edit, or on Save As to save in a new file.
The usual shortcut is Ctrl s
.
Choose a name for the file and an extension. The extension should be compatible with the language:
- For JavaScript, the extension should be
.js
. For instance,file.js
; - For Python, the extension should be
.py
. For instance,file.py
; - For Lua, the extension should be
.lua
. For instance,file.lua
; - For GDScript, the extension should be
.gd
. For instance,file.gd
.
My recommendation is choosing filenames without accents, spaces or special characters.
For instance, a_good_name.lua
instead of a potentially problematic name.lua
(which is even worse in Portuguese, because of an accent: um nome potencialmente problemático.lua
).
To learn usual shortcuts for text editing, check out text editors.
The First Program
This page's topic is console (terminal) output for programs. It is time to explore it, which was previously done in the configurations for development environments.
Text writing is an example of data output, one of the most important resources of any program. The output allows that a person receive the calculated and processed resources in a program. Without output, you would need to inspect electrical circuits and measure electric current to discover results. Although possible (for very simple programs and architectures), certainly it is not something practical, simple or convenient to do.
Console text writing is one of the most primitive, though useful, resources for programming. Albeit primitive, certainly it is more convenient and simpler than inspecting electric current.
- In JavaScript, you can use
console.log()
: documentation; - In Lua, you can use
print()
: documentation; - In Python, you can use
print()
: documentation; - In GDScript, you can use
print()
: documentation.
All previous resources receive a parameter (the value passed in between parenthesis), and write the textual representation of the value in the console.
// script.js
console.log("Hello, my name is Franco!")
# script.py
print("Hello, my name is Franco!")
-- script.lua
print("Hello, my name is Franco!")
# script.gd
extends Node
func _init():
print("Hello, my name is Franco!")
The first line of each code block provides a comment with a suggestion for the filename to store the code.
Next, console.log()
or print()
(depending on the language) are used to write text.
If you want to write more than one message, you can create a new line with new text in between double quotes.
For instance:
console.log("Once upon a time, a curious person decided to learn programming.")
console.log("She/he browsed to the website on the address https://www.francogarcia.com/")
console.log("She/he create a program to write in the console...")
console.log("Then she/he created many other programs...")
console.log("...")
console.log("And everyone lived happily ever after.")
print("Once upon a time, a curious person decided to learn programming.")
print("She/he browsed to the website on the address https://www.francogarcia.com/")
print("She/he create a program to write in the console...")
print("Then she/he created many other programs...")
print("...")
print("And everyone lived happily ever after.")
print("Once upon a time, a curious person decided to learn programming.")
print("She/he browsed to the website on the address https://www.francogarcia.com/")
print("She/he create a program to write in the console...")
print("Then she/he created many other programs...")
print("...")
print("And everyone lived happily ever after.")
# script.gd
extends Node
func _init():
print("Once upon a time, a curious person decided to learn programming.")
print("She/he browsed to the website on the address https://www.francogarcia.com/")
print("She/he create a program to write in the console...")
print("Then she/he created many other programs...")
print("...")
print("And everyone lived happily ever after.")
Each blocks provides a source code for the program Hello, World!
in the corresponding program language.
Source code is the artifact created by a programmer with the instructions that the computer should follow.
The machine does not use the source code, though it needs a special code to use, called machine code.
Thus, it is not enough to write the code and save it in a file.
You will need to use a tool called a compiler or an interpreter to convert source code into machine code.
You can learn the difference between them in this link.
For JavaScript, Python and Lua, you can use the interpreter directly to test the previous code instead of creating a file to store it. This is called REPL, as explained in the pages describing environment configuration for each language. For GDScript, you will need a file.
Are you using a browser in a computer (instead of a mobile device such as a smartphone or a table)?
If you using a modern browser in a computer, you can already test the JavaScript code via REPL.
Press F12
, choose Console
, and type the JavaScript code.
Next, press enter
(also known as return
) to evaluate it.
console.log("Hello, my name is Franco!")
The message Hello, my name is Franco!
should appear as a result.
For a more detailed and illustrated example of how to proceeded, refer to how to use the embedded console in JavaScript.
In a browser, you can also use alert()
(documentação) if you want to display an alert dialog.
For example:
alert("Hello, my name is Franco!")
The following button writes a message in an alert dialog. After pressed, the message will be shown in a pop-up dialog.
Buttons are not magical; they run souce code defined by programmers. The button provided as example defines the following code:
alert("Hello, my name is Franco!")
The adoption of JavaScript in this material is intentional. With the possibility of using the embedded console, you will be able to test the provided code for a mode dynamic learning. Likewise, you can change the code to test variations. In potential, you will also be able to observe errors. For instance, what does happen if you type a message without quotes?
Converting the Code From the File to a Program
I strongly recommend the use of an IDE by beginners. Some suggestion include:
Thonny
for Python;ZeroBrane Studio
for Lua;Godot Engine
for GDScript.
If you using an IDE (such as the recommendations Thonny
for Python or ZeroBrane Studio
for Lua), it suffices to use the play (🢒
) icon or use its shortcut key (normally F5
, though F6
can be more practical in ZeroBrane Studio
) to run your program (assuming it is correct).
The IDE will perform the required steps to convert your code into a program and run it.
Python, Lua and JavaScript
If you using a text editor, you will need to use the command line. The steps for Python, Lua and JavaScript are described in the following links.
As the three languages are interpreted, you will use the interpreter for each language to run the created source code file.
python script.py
lua script.lua
godot -q -s script.gd
All the previous command will result in programs that write Hello, my name is Franco!
and finish.
JavaScript
For JavaScript, the process is slightly different.
- You can use the embedded console, for tests.
Press
F12
, start the console (terminal) and type your code. Pressenter
(return
) to evaluate it. The console is an option for initial familiarisation. - You can create an HTML file and a JavaScript file to run the code in a local page. After using the console, you can start your Web development activities. Create the files and follow the steps described in the previous link to run JavaScript code in your favorite Web browser.
The HTML file can store the following code, adapted from the previous link.
It can be called index.html
; the JavaScript code must be called script.js
and be stored in the same directory of the HTML file.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Page Title</title>
<meta name="author" content="Franco Eusébio Garcia">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<header>
<h1>My Program</h1>
</header>
<main>
<!-- Comment. The name of the JavaScript file mustbe the same as defined below. -->
<script src="./script.js"></script>
</main>
</body>
</html>
Next, you should open the HTML file in your browser.
To do this, open the directory (folder) of your file using a file manager and double-click on index.html
.
After the page loads, open the browser's console (F12
); the message defined in script.js
should appear.
If you modify the code of the JavaScript (or HTML) file, you must reload the page in your browser (for instance, using the F5
shortcut).
Some text editors, such as Visual Studio Code
, allow to run JavaScript code as if they were an IDE.
Moreover, they can automatically reload the page in a browser whenever you modify a file.
If the HTML seems too complex, it is possible to simplify it. The minimum HTML file for text with correct accents would be something like the follow example:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
</head>
<body>
<script src="./script.js"></script>
</body>
</html>
The minimum HTML file for text without accents can be even simpler. In this case, ideally you should only use ASCII characters (in other words, English characters).
<!DOCTYPE html>
<html>
<body>
<script src="./script.js"></script>
</body>
</html>
In the minimum version, can you identify the structure of a JavaScript program embedded in a HTML page?
Results
The following image illustrates the code and the results for the programs written in this page.
The image shows:
The
Thonny
IDE for Python. The code is written in a file calledscript.py
, created using the IDE;The
ZeroBrane Studio
IDE for Lua. The code is written in a file calledscript.lua
, created using the IDE;The Godot Engine game engine for GDScript. The code is written in a file called
main.gd
, attached to a scene in the editor;The Mozilla Firefox Internet browser and the
Kate
text editor for JavaScript. The text editor has two files opened:script.js
, with the JavaScript code;index.html
, with the code for a Web page to use JavaScript in the browser.
The browser Mozilla Firefox has the page loaded. If you open the embedded console (shortcut:
F12
), you can visualize the written message.
You can use your preferred combination of text editor and Internet browser.
As commented in text editors, Kate, Notepad++, gedit, Atom and Visual Studio Code are examples of good text editors for beginners.
In the next topics, it is possible that images display the text editor that I usually use (GNU Emacs).
In the previous image, I have decided to use Kate to show the standard menu (with File
and New
to create files).
Text Formatting
Console writing often allows the use of some special combinations for formatting.
The following values can be found on a Linux system using the command man printf
.
They are also valid for many programming languages.
Combination | Effect |
---|---|
\\ | Write a backslash |
\' | Write a single quote |
\" | Write a double quote |
\n | Add a line break (LF) |
\t | Add a tabulation |
\v | Add a vertical tabulation |
\r | Add a carriage return (CR) |
\f | Add a form feed |
\a | Emit a beep (noise) |
\b | Add a backspace |
For instance:
console.log("Line 1\nLine 2")
console.log("Line3")
console.log("1\t2\t3")
console.log("Quote: \" backslash: \\ text continues")
print("Line 1\nLine 2")
print("Line3")
print("1\t2\t3")
print("Quote: \" backslash: \\ text continues")
print("Line 1\nLine 2")
print("Line3")
print("1\t2\t3")
print("Quote: \" backslash: \\ text continues")
extends Node
func _init():
print("Line 1\nLine 2")
print("Line3")
print("1\t2\t3")
print("Quote: \" backslash: \\ text continues")
In general, \n
(line break), \t
(tabulation), \\
, \'
, and \"
are frequently used and can be used in multiple programming languages.
Tabulations are useful to separate values.
Depending on the text width, they can keep values aligned.
The beep does not always work; it depends on the language and the chosen terminal interpreter. Some other values are not always available as well.
New Items for Your Inventory
Tools:
- Visual programming languages;
- Flowcharts;
- Interpreter;
- Text editor;
- IDE.
Skills:
- Conversion of source code to program;
- Terminal (console) writing.
Concepts:
- Compiler;
- Data output;
- Interpreter;
- Machine code;
- Program;
- Source code.
Programming resources:
- Resources to write text;
- Text formatting.
Practice
Write a program in the language of your choice about what you would like to create with programming. The text be of any size of want; what is important is to practice.
Next Steps
Congratulations!
Now you are, officially, a computer programmer.
It can be complicated to create and run the first program. However, after executing the first program successfully, programs that use only the standard library (that is, that do not use external libraries) will follow the same process.
Now you know how to create programs from diagrams or text, and run them in a computer. From now on, you can choose if you want to learn using visual or textual programming languages. The choice is indifferent when learning computational thinking. The computational thinking is the same, because it does not depend on programming language. The language can be written, visual or in any other modality; concepts that are learned for one modality are often applicable to others as well. Thus, you can choose the one you prefer.
To observe results, you have learned to use one of the most important programming resources: the data output.
At this first moment, you learned to use one of the simplest forms of data output, which uses the terminal (console). Perhaps that the resulting program does not have a beautiful presentation (except case you have used JavaScript and HTML), though it is usable and serve its purposes.
A little more knowledge is required to create multimedia programs, with windows, graphical user interfaces, sounds or vibrations. In rigour, you can already create them in JavaScript or GDScript, though you will need yet to be studies features.
Each step on its time. Before beauty, we should aim for understanding. After all, what, exactly, does a computer work with?
Coming next...
- Introduction;
- Entry point and program structure;
- Output (for console or terminal);
- Data types;
- Variables and constants;
- Input (for console or terminal);
- Arithmetic and basic Mathematics;
- Relational operations and comparisons;
- Logic operations and Boolean Algebra;
- Conditional (or selection) structures;
- Subroutines: functions and procedures;
- Repetition structures (or loops);
- Arrays, collections and data structures;
- Records (structs);
- Files and serialization (marshalling);
- Libraries;
- Command line input;
- Bitwise operations;
- Tests and debugging.