Yesterday I gave the kid his first lesson in code.

They have a computer class at school that’s fine so far as it goes. It’s mostly about how to deal with a user interface, type stuff, arrange pictures on a screen. They play educational games for spelling, names and facts about dinosaurs, arithmetic flash card races. All good, but they haven’t been teaching code.

We’re using php so he can code something and see it happen in a browser by clicking the page refresh button. I suppose we could use Python, or Java, or C or Visual Basic. Php was handy.

So yesterday we started with a simple loop.

All this does is write the word pizza on the screen two times. Nothing fancy, but it demonstrates some important beginning concepts, all of which are useful in the real world, too.

  • You always have to finish what you start. The opening angle bracket-question mark at the beginning needs a closing question mark-angle bracket at the end. The opening parenthesis needs a closing parenthesis. The opening squiggly bracket needs a closing squiggly bracket, the opening quote needs a closing quote. Computers hate it when you don’t finish what you start. So do most people.
  • ****You always need to say when you’re done. It’s not enough to finish what you start. You have to say, “this is done now.” Otherwise one thing runs into the next and things get too messy to deal with. In php code, every step ends with a semicolon. Other languages have other ways of saying done.
  • ****Assignment, comparison, and counting ( =, <, and ++ ). Sometimes you need to define things so everyone is clear about what they are. Once you know what things are you can compare them. (Is this number less than 2?) And sometimes you need to move on to the next number.
  • ***You can always write it down.***Echo is php’s way of saying “put this on the screen.”

There are a few other things here we’ll get to in future lessons. But the most important thing to learn from this little snippet of code is the power of a simple loop.

“I could just type pizza two times,” the kid said.

“Yeah, but what if you wanted to type pizza 100 times, or 1000 times?” I said.

“That would take me like 20 hours.”

“Exactly. But the computer is good at doing things the same thing over and over again really, really fast. So if you change the 2 to 1000, it will count to 1000 really really fast, and every time it counts, it will print the word pizza on the screen again until it’s done it 1000 times. Try it.”

He did, and of course, it did.

Then tried it with 10,000 and 10,000,000. The 10,000,000 took about 20 seconds, and it was kind of amazing to see how far down you had to scroll the screen to get to the bottom of 10,000,000 pizzas.

“It would have taken me like two years to type it ten million times,” the kid said.

“It would have taken you longer than your whole life,” I said.

“Cool,” he said.

And he was right.

Next lesson (which we already have sort of used in this lesson – $i): variables.