Chapter 4
IN THIS CHAPTER
Coding text-based information to appear onscreen
Accepting text input
Combining text input and other text
Creating a simple Mad Libs game
This chapter guides you through a simple but fundamental task in coding — placing text-based information onscreen. Whether you and your coder are building an app, constructing a webpage, or coding some other type of computer program, you need to show information, instructions, or messages onscreen to your user. This information may be text, symbols, or numbers presented in human language, to allow communication between people and computers.
The first program that almost every new coder writes is one that displays the words, “Hello world!” It’s a good way to get started as it takes little time to write such a program — a program that provides immediate gratification with its welcoming message. So say “Hello world!” (and a few other things) as you begin coding communications to display text.
On or off the computer, information and conversations use alphanumeric text and symbols to communicate. Before the days of ubiquitous laptops and smartphones, parents and teachers employed paper and pencils to write. The writings created (by hand!) took many forms: song lyrics, essays, and computations, even recipes! And each of these forms required a variety of characters, assembled in specific patterns, to make meaning. While all these characters can now be transmitted digitally via a keyboard and screen, you still use old-school methods of “working with words” — and doing so can help shape your understanding of how to code such text in your programs.
Try showing a little bit of text onscreen in a few different programming languages. Most programming languages provide some way to display text so that you can convey information or directions to the user. Each language has its own unique way of issuing this command, which is generically called a print command. The text isn’t printed on a printer, but is instead displayed on a computer screen or mobile device screen.
Every programming language is different, but a typical pseudocode expression for a print command looks something like this:
print ("words to be printed")
Some languages use single quotes, others use double quotes, and still others use no quotes surrounding the words to be printed, but this is the general structure.
Scratch’s version of print is the say
command — it's used whenever you want to make a sprite speak or think text phrases. Figure 4-1 shows an example of a command block using say
, and the resulting output.
When the sprite is clicked, anything your kid types into the say field is displayed in the speech bubble by its sprite object. The think
command performs the same task using a thought bubble instead of the speech bubble.
In Python, you can show some text onscreen by using a print()
command, followed by the phrase in single or double quotes inside the parentheses. Figure 4-2 shows an example of a command block using print()
, and the resulting output.
Python requires you to use quotes (single or double) around the phrase you want to print. The phrase and quotes are enclosed inside a set of parentheses.
When building a simple webpage, a great deal of what you show onscreen is text. Webpages use HTML (Hypertext Markup Language) to display that text. HTML is more of a formatting language than an actual coding language. But because you and your kid likely want to tinker a bit with HTML, take a look at a simple example of how you can display Hello world! in a web browser:
<html>
<body>
<h1> Hello world! </h1>
<p>I live a fascinating life, how about you?</p>
</body>
</html>
Use Notepad (Windows) or TextEdit (Mac) to type the short text file — or “program” — shown here. Don't focus too specifically on the details at this point; just note a couple of key ways in which you can place text on a webpage. Any text you type between the <h1></h1>
tags, called Level 1 heading tags, appears as a large heading. Any text you type between the <p></p>
tags, called paragraph tags, appears as standard text. Save the file with an .html
extension.
Double-click a .html
file; it opens in a browser similar to the one shown in Figure 4-3. Now you can see your words on a webpage! For step-by-step instructions on building a simple webpage in HTML, see Chapter 14.
In JavaScript, there are a few different ways to show text. One way is to place text into a text label for display in an app. The App Lab at Code.org provides a fun and easy way for your kid to tinker with using JavaScript to display a bit of text on a mobile device emulator. As shown in Figure 4-4, the JavaScript command tells the textLabel
named greeting
to display the text phrase Hello world!
Someday, your coder might take AP Computer Science A, perhaps as a high school student in the near future. What that day comes, he or she will likely use Java as the programming language in the course. The first programming command taught will most likely be a print command:
System.out.println ("Hello world!")
To test this, you need to install an IDE (Integrated Development Environment) for the Java programming language. That is a mouthful, and not something you have to worry about just yet, but it’s good to know that the introductory skills you’re helping your child build now are leading up to some real-world programming skills she can use in the future!
So far, you’ve only seen how to display text onscreen to communicate information to the users of your program. Text you “put out” from your program is called output. But how do you create interaction using text? Accepting text into a program is an important way to create interactivity in your code. The term input is used to describe “putting in” text (as well as other content, such as numbers). Your coder can write a program that asks for a person’s name, saves that name, and then displays the name later in another part of the program.
You’ll need a variable to store any piece of information the user inputs to your program. A variable is something that can change its value. For example, the variable name
could store the value “George” at one time, and “Maria” at another time. Think of this storage process in the same way that your brain stores a snippet of information that is input through your eyes or your ears. We cover variables in much greater depth in Chapter 7. At this introductory stage, just know that your coder needs to include in his program the code for a variable to store a piece of information input by a user.
In Scratch, you can accept user input using a simple built-in variable called answer
. Scratch pairs the answer
code tile with an ask
code tile because the two commands form a natural pair. For example, the code block shown in Figure 4-6 asks the user, “What's your name?” and then waits for a response. The user types her name into the input field at the bottom of the GUI, and this input is stored in the variable answer. The answer
variable is a temporary variable — it contains the user’s name until the user inputs something else in another ask and answer code pair. Then, this value of this new input replaces the value previously stored in answer
.
After you get an answer, you can use the value stored in answer
. For example, you can now show the stored name or words onscreen: Figure 4-7 shows how Scratch Cat can think
the answer as though he's pondering your name deeply.
In Python, you accept user input by creating your own variable to store the input. You can investigate additional details about Python variables in Chapter 7. But for now, just open a Python editor, such as the one available at pythontutor.com (see Chapter 3). Then type the simple code shown in Figure 4-8 to accept a word in and print a word in Python.
In this code, you create a variable called name
and ask for the user to input
a value to name
by asking, 'What is your name?'
Then, you print
the value of name
as output.
When you execute this code, you obtain the results shown in Figure 4-8: a console asking you to submit the name, followed by a printout of the name.
To create an interactive webpage that accepts user input, use HTML and JavaScript together. The following code shows how you can ask a user for their name, submit the name with a button, then show the name onscreen:
<!DOCTYPE html>
<html>
<body>
<p>What is your name?</p>
<input id="userInput"> </input>
<button onclick="submitname()"> Submit </button>
<p id="demo"></p>
<script>
function submitname()
{
var name=document.getElementById("userInput").value;
document.getElementById("demo").innerHTML = name;
}
</script>
</body>
</html>
Use Notepad (Windows) or TextEdit (Mac) to type the code shown here. The JavaScript code is located inside the <script></script>
tags, as shown in Figure 4-9. The code outside these tags is mostly responsible for formatting the information on the page and for calling the JavaScript code. Save the file with an .html
extension. For additional details on coding webpages, see Chapter 14.
Using JavaScript in the App Lab at Code.org, you and your coder can write a simple program that asks a user to type his name and then press a button to submit. The program then shows the name onscreen in a smartphone emulator. Figure 4-10 shows the code.
The code consists of two parts: “set up display” and “set up button event to produce name.”
The “set up display” part is comprised of two text labels, a text input field, and a button. Line 2 shows a text label called intro
that displays the text “What is your name?” This label is positioned by default in the top-left corner of the screen. Line 3 shows a text input field called nameField
that displays “ ” (blank space); this the where the user types his name. The Line 4 code creates a text label called greeting
that displays “ ” (blank space). This label is positioned in the location where the greeting is placed later. In Line 5, the command setPosition("greeting", 10, 150, 100, 100)
places the greeting label 10 pixels to the right and 150 pixels down from the top-left corner of the screen; it also makes the size of the label 100 pixels wide and 100 pixels high. Lastly, the code in Line 6 creates a button called submitBtn
that shows the word Submit
. This code is followed by a setPosition
command in Line 7 that positions and sizes the button.
The “set up button event to produce name” part begins on Line 9 with an onEvent
event handler, which causes the function makeName
to execute when clicked. The function makeName
creates (in Line 10) a variable name and sets it to the value of the text entered into nameField
. In Line 11, nameField
is hidden so that the user's entry is removed from the screen. Finally, in Line 12, the textLabel
greeting field displayed the value of the name variable.
Figure 4-11 shows the operation of the word in, word out program in the smartphone emulator.
Your kid likely wants to write code that combines the processes of accepting text input and printing text onscreen. Now that you know how to perform each of these tasks separately, you can put them together!
One common example of combining text from different sources is to ask a user for his name, store it in a variable, and then print a greeting that includes the name in the text, along with some other words. A pseudocode expression for this combined print command looks something like this:
print ("Congratulations " + name + ", you won a million dollars!")
Connecting text together, whether it’s individual characters or complete words, is called concatenation.
In Scratch, you can concatenate text using the join
command tile as shown in Figure 4-12. The join
command is located in the Operators category. Note that you can concatenate both variable names and literal text, adding as many join
tiles as you want! The output shows how join
allows you to make your program say complete sentences, customized for the user!
In Python, you can concatenate text using the +
command shown in Figure 4-13. Variable names and literal text can be put together, adding as many +
commands as needed. Literal text requires quotation marks around the text, while variables do not.
Most other languages your kid encounters use the + code to concatenate text for print output. Follow this format shown here!
age = input("How old are you? ")
print(name + " is " + str(age) + " years old")
Your coder may be expressing an interest in formatting text onscreen to give it a more organized appearance, or even some flashy and fun flair! Some programming languages, such as Scratch, don’t provide this option. But most programming languages, such as Python, provide codes for special characters and for creating line breaks. For example, this Python command uses a
code to indicate where a line break occurs:
print("To be
or not to be,
that is the question.")
This line of code prints like this:
To be
or not to be,
that is the question.
When formatting text for display in web pages, HTML — the “language of the web” — provides a wide ranges of options. Here is an example of HTML code demonstrating some of these formatting options:
<!DOCTYPE html>
<html>
<head>
<title>Greetings from the Web</title>
</head>
<body>
<h1>Formatting Text on the Web</h1>
<br>
<h2>You can use simple HTML tags to format your text.</h2>
<i>Are we having fun yet?</i>
<b>I'm glad you are!</b>
</body>
</html>
Figure 4-14 shows how the HTML appears when viewed in a web browser.
Table 4-1 presents several text formatting codes, or tags, your coder can use when creating her HTML code.
TABLE 4-1 Some HTML Text Formatting Codes
Code |
Example |
What It Means |
<b> Howdy! </b> |
Howdy! |
Bold text |
<i> Howdy! </i> |
Howdy! |
Italicize text |
H <sub> 2 </sub> O |
H2O |
Subscript text |
E = mc <sup> 2 </sup> |
E=mc2 |
Superscript text |
<h1> Big Idea </h1> |
Big Idea |
Heading Level 1 (there are 6 levels) |
They lived happily ever after. <br> The End. |
They lived happily ever after. The End. |
Insert line break |
Now that your coder has learned the basics of writing code to input, format, and output text in a computer program, he undoubtedly wants to do something fun with his new skills. Creating a Mad Lib story is the perfect culmination of the skills acquired in this chapter. A Mad Lib is a short, silly story that is missing a few words. Two players play Mad Libs together, with one player asking the other player for words that are used to fill in the missing words. However, the player supplying the words doesn’t know “the rest of the story” or how those words will be put together.
First, as outlined in Chapter 2, invite your kid to “think aloud” with you about the big picture of creating a Mad Lib. Here are some steps you and she might brainstorm:
After you and your coder have brainstormed the process for designing and creating the Mad Lib program, your coder might choose to devise a flowchart for the program code. Chapter 2 provides guidance in creating such a flowchart.
Finally, your coder may choose to translate the flowchart into pseudocode (see Chapter 2), or else jump right into writing code for the Mad Lib program. You and your coder can write the Mad Lib program in any language. Figure 4-15 shows an example of the code written in Python.
Figure 4-16 shows the output and result of the Mad Lab program in operation. Invite your coder to get creative by adding new variables and literals to her program. The program can be as short and silly, or as long and laughable, as she wants it to be!
3.133.137.17