Python #2

Okay, that first program was very simple. The next couple of ideas I want to introduce are comments and variables. If you put the “#” sign at the start of a line, the computer ignores it. Programmers use commenting to make their  code more readable for human beings. Here’s a short program that includes some comments and a variable.

The comment lines are here to explain what is going on.

Next, I create a variable called “name” and use it to store the string “antiloquax”. Strings are a type of variable that stores things simply as a string of characters. You can’t do maths on strings, so if you want your variable to store numbers for doing calculations, you have to use define it differently (we’ll cover this soon).

So, now when the computer prints: “Hello”, it also prints whatever is in the memory “box” called “name”.

That’s all well and good, but it would be nice to interact with the computer a bit. This next version of the program introduces inputs.

The input command makes the computer expect an input from the user. Whatever you type in goes into the variable “name”. I’ve made a slight addition to the print command in order to add a full-stop to the end of the line!

Al this is quite simple, I think you’ll agree. I’m going to introduce the “if” command next.

The if command is very important. Sometimes we want the computer to make a decision based on a condition. You can see what is happening here: if the user enters the name “mark” then the computer says hello. If some other name is entered, the computer prints the longer statement saying it doesn’t know the user.

There are a couple of important points to remember about this. Firstly: when we are comparing two values to see if they are the same, we use 2 equals signs, in Python. Secondly, at the end of the if statement (and the else statement) there’s a colon. Thirdly, the line  (or lines) following the colon are indented. This makes it very easy to see the parts of the program that are only going to be used if certain conditions are met.

Right, that’s all for now!

antiloquax

Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: