Can We Escape the Forever Loop?

If you’ve used Scratch or a similar program to teach coding, it’s likely you’ve helped a student who asked why code like this isn’t working:

When green flag clicked - if(space key pressed) - Move(10)

The student is pressing the space key, but their sprite isn’t moving. They don’t understand why.

“Well,” you say, “that’s easy. What’s happening is the code’s only running once, and it happens instantaneously, so if you’re not already holding down space when the program starts, it sees that the key isn’t down, moves on, and ends the program. All you need to do is wrap it in a forev-”

And I’m going to stop you right there, before you doom the kid to a loop he probably won’t escape for years. Let’s go back in time. It’s likely you at some point learned to code using some kind of a console app, maybe Python or if you are as old as me maybe BASIC. In any case, you probably have written a HelloWorld2 program that went something like this:

name = input("Hi, what's your name?")
print("Hello " + name + "!")

Now let me ask you this. Why do you not need to do something like this?

while(name == "")
    name = input("Hi, what's your name?")
print("Hello nice to meet you " + name + "!")

In other words, how does the compiler know to just sit there and wait for you to enter your name before just moving on and running the program and printing “Hello  !”

If your answer is, “Well, that’s just how console apps work!” then I am a bit disappointed but I’ll give you another chance. Why do console apps work that way? In pretty much any console app, when you use an input command, it knows to sit there and wait until the user has entered some data ending with a linebreak (‘enter’) character.

Formally in programming this is known as an ‘event’. This is any change in state of the compiler’s environment; an event is often user input but doesn’t need to be. It can be a mouse click but it can also be the return of data from a network call or two objects colliding in a video game.

In a simple procedural program the only way to check for an event is to create an endless loop and check repeatedly 30-60 times a second. It’s not just Scratch that does it this way. Processing (and Processing JS in Khan Academy by extension) has the draw() function, which is just a forever loop. Greenfoot has the act() function, same thing. Even Arduino C is centered around the loop() function.

Except for the Arduino, all these are primarily game-creation engines. But real programmers rarely use a continuous loop like that. Most programs with user interaction are instead event-based. This means you create a handler that responds to an event like a mouse-click or key press. In JavaScript, for example, it’s something like this:

document.getElementById("myBtn").addEventListener("click", displayDate);

But that’s advanced programming! You can’t expect a simple program like Scratch to have event handlers. Oh yeah? How about this:

When (space) key pressed - Move 10 steps
An event handler in Scratch!

If you put in the above, it works out of the box. No Green Flag Clicked necessary. Oddly, I always thought of this as the more “basic” approach, probably because there is nothing to “start” the program. But really it could be seen as the more sophisticated approach. They have the start of full event-driven programming. Imagine if they had a block like this:

On event ( ) do:
The event handler Scratch should have

With something like this you would probably still have a few things stuff in the forever loop, but almost everything else – key presses, mouse clicks, collisions, changes in variable values, appearance and disappearance of sprites, etc. etc. – could depend on event handlers. Ideally there would be something to “turn on” the event handlers too, whether a green flag clicked or whatever. There is no reason that couldn’t be in there.

But what difference does it make? Why is the forever loop so bad?

Well, for one thing, if you ever want to teach any other kind of loop it is really difficult to come up with a way to work it in, because it’s already looping. If you try to loop something inside that, it will stop all the rest of the action of the sprite. If you want to iterate, or have a conditional loop, you have to kludge it by creating a counting variable or condition and checking it repeatedly in the forever.

But in an event-driven program with multiple different event “threads” (weird, Scratch has threading too!), other handlers could respond to different events while a previous thread is still executing. This gives you an opportunity to put different kinds of loops in.

More importantly, though, it would give students a better idea of how most programs actually work. They could create an interactive environment like a modern web page.

Also, you will help them understand that a loop that repeats forever without a built-in interrupt condition is normally a really bad idea. Really there usually is some kind of interrupt, whether the stop sign or the pause button in Greenfoot and so on. But that’s outside the program the students are writing.

More importantly, we could get away from the idea that the only reason for programming is to make video games. We’re never going to get anywhere with coding education until kids start making programs that do real things, not just play.

Teaching coding: The missing steps

It seems like every day someone is introducing a new tool to get kids into coding. Just recently Apple introduced their Swift Playground, with animations of kids making a weird pear-shaped blob thing move around a 3D world. We have the now-venerable Scratch, and Scratch Jr. for the really little kids, we have Hopscotch, we have the Hour of Code, we have Khan Academy coding and new tools that allow kids to program robots with Scratch-like code chunks. So that means that this generation should produce a huge new batch of computer-literate coders, right?

Missing Steps
Some steps are missing

Alas, probably not. I’m glad these first steps to coding are there, and they are essential. We also have plenty of steps higher up the mountain where adults, college-age kids or particularly motivated high-schoolers can learn more advanced coding: places like Udacity, Coursera, Pluralsight, Code School and so on. What we lack now is the tools, and maybe more importantly the teachers, to get people from these lower steps to the higher ones. It’s like staircase with the middle twenty steps replace by ropes and those wall-knob attachments from rock-climbing gyms. Some people will still get to the higher steps, but not many. Most will get to the top of the bottom row of steps, look around and say “that was fun, I made the robot move and turn; I wonder what we’re doing in art?”

But that’s fine, right? So most kids don’t go on and learn about networking. That’s advanced computer stuff! It’s not like every single computer is attached to some giant computer netw…oh.

Today we’re surrounded by computers, but unlike even ten or fifteen years ago, almost none of those computers does anything by itself!

Even applications that were once entirely local, like Microsoft Office or the Adobe Creative Cloud projects now depend on regular network connections. Remember the last time you were in a coffee shop and the WiFi didn’t work? I bet you didn’t get much done. You probably just put your computer away and got a book out or interacted with actual humans. Almost all computer work today involves having to download something from somewhere or look something up on Google. Even games are networked more often than not.

And it’s just going to get worse. More and more services are moving to the cloud; lots of organizations don’t even use Office anymore in exchange for Google Drive. More and more jobs involve getting complex data from a big cloud using APIs. And when the Internet of Things blows up, even your toaster will have an API.

Move the things around the little screen
Code can do ANYTHING!…in that window

But the programs the kids are learning to do, even a fairly advanced learning environment like Greenfoot that uses actual Java and begins to teach kids about objects and classes, all basically involve moving little shapes around a little screen on the side of the code. And sure sometimes you can blow the little screen up to your full screen, but it’s still a cozy little sandbox that has no contact with the rest of the world, unlike pretty much every other app they interact with.

I’m not saying there is anything wrong with these programs! I use many of them in my teaching. But there are very few places to go now when a kid is ready to get outside of that sandbox. Sure they can start learning Python, and if they’re patient they’ll stick with writing console apps for a month or two until they are able to start using PyGame and make some graphics. They can get into physical computing and start learning Arduino if they have the electronics gear and other hardware to make it possible. But as I mentioned, most Arduino programs (of the sorts most kids do) are actually very simple.

What is needed are tools that make it easy for kids to make simple network requests and access simple databases, tools that take some of the hard parts out (like making complicated database connection strings or working out complex network handshakes), while allowing kids to do the part that’s actually not that hard.

And the ideas aren’t that hard! SQL queries like “SELECT temperature FROM WeatherDatabase WHERE year>1990” or adding parameters to an http query like “?field=accidents&city=Omaha” are not that hard to to understand even for a middle schooler. But getting to the point where you can do that is. For now. It’s time for a tool to change that.

 

 

Coding Instruction: Beyond Video Games

Scratch Cat at WorkI love teaching kids to make video games. I’ve done this for quite awhile now, using a lot of different languages, including Python, Scratch, the JavaScript/Processing port at Khan Academy, the Greenfoot Java IDE, full Java with Eclipse and the once-promising XNA platform in C#, killed in its youth by short-sighted Microsoft executives (though resurrected as open source code as Monogame). There is a lot to recommend teaching coding this way. Kids love to play video games, so it makes sense they’d love making them. And starting by creating a sprite and moving it across a screen is way more interesting than another “Hello World” program. But the more I do it, the more aware of the limitations.

One important limitation is that making a video game, much like making a website, is not entirely or even mostly a coding task. A big part of making a video game is actually graphic design. Much as they say there are really only a few basic plots in fiction, there are really only a limited number of different types of “actions” in a video game, especially a simple 2D one of the sort a student would hope to make. Once you get that working, it’s mostly about how your sprites and backgrounds look. Designing sprites and backgrounds is an interesting challenge in itself, but it’s a different skill from coding and a distraction from a coding class. Often I have to make hard decisions about how much time I want to let kids spend looking for or designing game sprites, because on the one hand the small number of sprites built into most gaming platforms is limited and quickly gets boring, but on the other hand I am teaching coding, not graphic design.

Furthermore, though these different platforms mostly make beginning a game very easy (with the exception of Java, which has a lot of hills to climb to even make a game window), often students quickly hit a ceiling when they start wanting to do things that the pre-designed built-in “move” and “turn” methods don’t let them do.

When they hit this limit, one of several things happens: some kids get bored and want to quit, some kidsCommands Scratch doesn't have doodle around and do the same thing over and over, and a smaller number of kids push against the limits of the platform. This can lead to some incredibly ugly code in a limited platforms – I’ve seen people build a scrolling platformer with Scratch, but it’s like painting your house with a nail polish brush, and the code is about as attractive. Other platforms have less of a ceiling; Greenfoot contains within it the full capabilities of Java, so theoretically you can do anything, but it’s a huge stretch to get from making a single-screen game with limited sprites and objectives to the sort of games kids imagine, with things like scrolling, jumping with gravity-like motion or different kinds of 3D.

So what’s the alternative? There’s always the “traditional” coding class, where students use Python or some other interpreted language to create text-based programs that say things like “Good job Jim you guessed the correct answer in 2 tries!” But as I argued in an earlier post, that’s exactly the kind of coding class that teaches everyone except natural programmers that coding is boring and not for people like them.

Arduino Uno boardPhysical computing, such as working with Arduinos, is definitely an area of potential here. I will be working with students making Arduino projects this year, and I’ll report on how it goes. As with games, physical computing involves working with things that are interesting learning tools in an of themselves but are not actually programming. More significantly, most Arduino programs, at least of the sort students do, are very simple, and may not touch on many advanced concepts. The difficult part of physical programming is usually the physical part. And anyways, you aren’t always in an electronics lab; sometimes you just have the computers to program with. So what else can you do?

no_northwindI’ve been thinking about this a lot, and it came to me the other day: students really need to do is work with data. Real data, not the Northwind database or fake lists of names from the phone book. Data about the real world, like climate records, health surveys, demographic information, data that allows them to address real problems in the world. But where do they get the data? And how do we get it in a format that they can work with it?

I have thoughts about this, but it’s too much to add to this post. I’ll be addressing my ideas about how to get real data in the hands of students in future posts.