Friday, December 7, 2012

Hello Crispin!

In the last post we got the computer to say hello to the world. Now we want to get a bit more personal. Before we start, let's introduce a name for those three little arrows you see on the screen. They are called a command prompt or more often just a prompt. That is because the computer is 'prompting' you to type something in for it to do. It's also a lot easier than saying 'three little arrows' every time. So, at the prompt, type the following:

>>> name = 'Crispin'

Now hit enter and type:

>>> print 'Hello ' + name

Hit enter again, and see what you get. If all goes well (and you typed carefully) you should see:

Hello Crispin

Of course, if you were particularly clever, you may have put your own name in, in which case you would see something else (unless your name is Crispin)

Now, a little secret: programmers are lazy. If there's an easy way to do something, you can be pretty sure a programmer will make it happen. On your keyboard, hit the 'up' arrow once. You should see the 'print' command you typed in appear again. Hit enter. Hey presto, we got the computer to do talk to us with two key strokes. Now, do the following:
  1. Hit the 'up' arrow twice. You should now see the name = 'Crispin' line again.
  2. If you now hit the backspace key (normally next to the key with a + and = on it) you will see it starts to delete what you wrote.
  3. Do this again until you have removed your name
  4. Now type in your friend's name (don't forget the quotes) and hit enter.
  5. Now hit 'up' again until you see the print 'Hello World' + name and hit enter again.
If all is well you should see the computer say hello to your friend!

You have just created and used your first variable. When you typed name = 'Crispin' you created a variable called 'name'. You then assigned the value 'Crispin' to that variable.

If that seems a bit tricky, think of a variable as an empty cardboard box. Imagine writing 'name' on that box. Now write your name on a piece of paper, and stick it in the box. That's what you did with name = 'Crispin'. When you then wrote print 'Hello ' + name you said to the computer, "print 'Hello ' and add the contents of the box labelled 'name' to it".

When you changed the name variable to your friend's name, you were taking out the piece of paper with your name on it, and putting your friend's name in instead.

No comments:

Post a Comment