PROJECT 2
In Project 1, you install Python and fire up the interpreter. Project 2 gets you into Python proper, transforming you from an ordinary member of the public into a full Python programmer in training.
Tradition dictates that Hello World! be the first program that you write when you’re learning a new programming language. You’re following in the footsteps of many great programmers when you create this project.
In this project you see how to communicate information from the program to the user by making (outputting) a simple message. You see how Python remembers information and how you can name the information that you’ve asked Python to remember. This means you can reuse the information in other parts of your program.
You’ll see how Python makes its way through your programs, how to stop a program if it goes nuts, and how to make a program go a little nuts (to test how to stop it). Finally, check out some core program techniques (called loops), which you’ll use to cover the screen with greetings.
To create your Hello World! program, follow these steps:
Open your Start menu and choose Python (command line).
You pinned it to the menu in Project 1. You should get a prompt that looks like >>>
.
Code listings in this book are formatted in a different font to show you that they’re Python code.
At the moment, you’re doing everything in interactive mode in the Python interpreter. That’s where the >>> comes in. Python shows you >>> when you’re supposed to type something.
print('Hello World!')
Press the Enter key.
Python runs the code you typed.
You see the output shown in Figure 2-1. Congratulations — you’ve written your first program. Welcome to the Python-programmers-in-training club.
If you don’t see what’s in Figure 2-1, check that you typed in the text from Step 2 exactly as it’s written:
The Python interpreter takes in each line and operates on it immediately (more or less) after you press the Enter key. In Hello World! you use Python's print feature. print takes what’s inside the parentheses and outputs it to the command line (also called the console).
Python is sensitive to both the grammar and punctuation. If you misspell something, the program won't work. If Python is expecting special characters and you don't put them in, then Python will fail. Some Python issues are shown here. Can you work out how you would fix them?
>>> pritn('Hello World!')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'pritn' is not defined
Here’s another:
>>> print('Hello World!)
File "<stdin>", line 1
print('Hello World!)
SyntaxError: EOL while scanning string literal
Here’s another:
>>> print 'Hello World!')
File "<stdin>", line 1
print 'Hello World!')
^
SyntaxError: invalid syntax
Python tries to give you the reason it failed (that is, NameError and SyntaxError).
Check each of these things:
In Hello World!, the message that print is sending is called a literal. Think of a literal as being something within single quotes. (Single quotes are this ' instead of double quotes, like this ").
Literals are the rocks (not rock stars) of the programming world. You can pick them up and throw them around, but you can't change them. They can exist by themselves in a program, but they don’t do anything:
>>> 'Hello World!'
'Hello World!'
That's a program that has only a literal and nothing else. It’s just a little bit different from the Hello World! program. In that program there were no quotes in the text that Python printed, but in this example the second line has single quote marks around it.
Python doesn’t judge the content of a literal. That means you can misspell it, fill it with weird words, and even fill it with weird, misspelled words. You still won’t get an error message from Python.
The single quotes are important. If you leave them out, Python thinks the text is telling it to do something. In this example, Python doesn’t know what Hello and World are supposed to do:
>>> Hello World!
File "<stdin>", line 1
Hello World!
^
SyntaxError: invalid syntax
The literals mentioned here are all string literals. String literals are read like text, instead of like a number. (I don't know why they are called string literals and not something else, like alphabetical literals.)
You can make a sequence of characters into a string literal by putting a single quote on each side:
Hello World! → 'Hello World!'
However, watch what happens when you make a literal from something that already has a single quote (like the word didn't):
>>> 'didn't'
File "<stdin>", line 1
'didn't'
^
SyntaxError: invalid syntax
Python reaches the second single quote and thinks that it marks the end of the string literal — but that’s not where you wanted it to end.
>>> "didn't"
"didn't"
>>> '"I have a very eely hovercraft," he said.'
'"I have a very eely hovercraft," he said.'
Ways you can create string literals include such diverse elements as single quotes and double quotes. But that's not all! You can also use triple single quotes and triple double quotes to create string literals. Seriously:
>>> '''This is a literal made with triple single quotes.'''
'This is a literal made with triple single quotes.'
>>> """This is a literal made with triple double quotes [sic]."""
'This is a literal made with triple double quotes [sic].'
Make sure you can create at least one literal that has a single quote, one that has a double quote, and one that has both a single quote and a double quote.
Okay, so you’re a master maker of string literals. After Python defines a literal, it sort of forgets it (like you might forget to do your chores). Python stores literals in memory then thinks they aren't being used so throws them out in a process called garbage collection. (No, I’m not making that up.) Sort of like when you leave something on the floor and it gets thrown in the trash because someone thinks you're not using it.
You name a literal like this:
Here are a couple of sample names:
>>> my_message = 'Hello World!'
>>> my_second_message = 'This name is a little long. Ideally, try to keep the name short, but not too short.'
Each name you use must comply with (follow) these rules:
Use a name to refer to what you've named. Each time you use a name (except on the left side in an assignment), Python acts like you’ve retyped in full the value that’s referenced by the name.
A value is something that’s referenced by a name. In the earlier examples, the only values are literals. You’ll see different kinds of values in the later projects.
You could rewrite your Hello World! program like this:
>>> my_message = "Hello World!"
>>> print(my_message)
Hello World!
This assigns the name my_message to the literal "Hello World!". (Remember, the name goes on the left side of the equals sign and the literal goes on the right side of the equals sign.) Then prints the literal that you named my_message.
When you’ve created a name, you can change what it names by using the same naming process for a different literal. Or, use another name (since referencing the name is the same as retyping it). To refresh your memory, this is the code from earlier in the project:
>>> my_message = 'Hello World!'
>>> my_second_message = 'This name is a little long. Ideally, try to keep the name short, but not too short.'
Now, bend your mind and assign the second name to the first name and print it:
>>> my_message = my_second_message
>>> print(my_message)
This name is a little long. Ideally, try to keep the name short, but not too short.
>>> my_message = 'A third message'
>>> print(my_message)
A third message
>>> print(my_second_message)
This name is a little long. Ideally, try to keep the name short, but not too short.
>>> my_message = 'Hello World!'
Also notice that the value of my_second_message didn’t change. The only thing that changed during an assignment is the variable name on the left side of the equals sign.
You can assign numbers to variables and add, subtract, and compare them:
>>> a = 1
>>> b = 2
>>> print(a)
1
>>> print(b)
2
>>> print(a+b)
3
>>> print(b-a)
1
>>> print(a<b)
True
This example uses very short names indeed! The symbol < means less than. a<b is asking Python whether it’s true or false that a is less than b. In this case, a is 1 and b is 2. a is less than b, so Python identifies this as true, and prints True.
You can even refer to the same variable on both sides of the equals sign to change what the variable is holding. For example, to increase the variable a by 1, you’d do (using the value a=1 from the preceding code):
>>> a = a+1
>>> print(a)
2
Here, Python looks up the value of a, increases it by 1, then stores it back in the variable.
Usually you get called rude if you interrupt. Not here. Are you ready to create a program that never finishes by itself (called an infinite loop)? This section shows you how to force it to stop.
Here’s how you write an infinite loop program:
This is what you’ll see:
>>> while True:
… pass
…
The Python interpreter is unresponsive. If you try to get it to assign or print something, nothing happens. It lays there like a lump. The usual >>> prompt isn’t there. You may also hear your computer laboring.
Quick: Press Ctrl+C to break out of the loop and get control back. You get this when you do it:
>>> while True:
… pass
…
^CTraceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyboardInterrupt
>>>
Did you notice the while statement in this code block? The while statement repeatedly executes (runs) a code block while a condition is satisfied.
A condition is any formula that has an answer of either True or False. If the formula is true, then the condition is satisfied. Otherwise, it’s not. In this example the condition was just True, which is, you know, true. So the condition is always satisfied.
There is another example in the following code. When you’re typing it, you must
What’s happening here? The numbers from 3 to 10 print out. Python runs print(a) eight times (count them!), even though the program only has one print statement.
>>> a = 2
>>> while a < 10:
… a = a+1
… print(a)
…
3
4
5
6
7
8
9
10
The first thing Python encounters in this example is the while keyword. This keyword tells Python to keep repeating the next block of code while a condition is true. In this case the condition is a < 10. The code block is the two lines a= a+1 and print(a). How can you tell this is the code block? First, the colon tells Python “I am about to give you a code block.” Second, Python defines its code blocks by whether the indentation of the code lines up. Since both of these lines are indented by four spaces, they are considered the same code block.
When Python first enters the code block that you just created, the variable a had been set to the value 2. It increased by 1 in the first line of the code block (a = a+1), so the first printed value is 3. The code block ends when Python has finished this print. Python then goes back to the top of the block and checks the inequality condition. Since a is now 3 (and less than 10), the code block repeats — a increases to 4 and is printed. This continues until a reaches 9. When a equals 10, then a is no longer less than 10. The condition (a < 10) isn’t satisfied and Python stops processing the while.
This structure is called a loop (in this case a while loop) because Python loops through the statement’s code block while the condition remains true.
The first while loop was very short, but made the computer work after a little while (no pun intended). It looked like this:
>>> while True:
… pass
This was the first multiline program you entered into the interpreter. It also didn’t seem to do anything. That’s largely because it used the pass keyword.
The pass keyword tells Python to pass over this line. It’s a bit odd to include an instruction that doesn’t do anything, don’t you think? pass is there because when Python sees a keyword like while, sooner or later it runs into a colon (which looks like this :). This colon signals to Python that it’s about to get a block of code. The interpreter complains if it doesn’t get a code block like it’s expecting.
See for yourself how upset it gets:
>>> while True:
…
File "<stdin>", line 2
^
IndentationError: expected an indented block
Officially, Python has 31 words keywords:
Try to assign something to the keyword return and you’ll fail:
>>> return = 4
File "<stdin>", line 1
return = 4
^
SyntaxError: invalid syntax
If you get an invalid syntax error message when you’re trying to assign a value to a variable, you’ll know why.
You can spread greetings of happiness across the screen when you know about loops. Type this in and add a comma at the end of a print statement (in this case after print(my_message)) and don't forget to press Ctrl+C to stop!
>>> my_message = 'Hello World!'
>>> while True:
… print(my_message),
…
What’s with the comma? Each time you call print, you get a message. The next time it prints, the output starts on a new line. When you add a comma at the end of the print, the next time it prints, the output starts from where it left off without adding a new line.
When I was young, my favorite was something like this. Who am I kidding? Figure 2-2 shows one of my favorite programs now:
>>> message = 'Brendan is Awesome!!'
>>> while True:
… print(message)
…
It's pretty neat to cover the screen with Hello Worldness, but it's a drag to press Ctrl+C to stop the program. You also run the risk of overtaxing your computer if you let it run too long.
It’s better to print the message only a certain number of times. You could do that with the while command. But you can use the range() command, which is for counting between numbers:
>>> range(3)
[0, 1, 2]
range gives you the numbers from 0 up to — but not including — the number in the parentheses (in this case, 3).
Notice that you get the numbers less than the number given to range. You might think it's a little strange for range to start at 0 instead of 1. You might also think it’s strange to leave out the number you want it to count to. Is that madness?
This form of counting (starting from zero) is called zero-based counting or numbering. A whole bunch of complicated reasons boil down to “It makes calculating a heap of things easier.”
You can use range to count from one number to another if you put the first and last numbers in the parentheses separated with a comma:
>>> range(3,10)
[3, 4, 5, 6, 7, 8, 9]
Here Python counts from the first number up to — but not including — the second number. It can even count in steps. To do this, you add a third number for the size of each step. To get the odd numbers from 3 up to 10, start at 3 and go to 10 in steps of 2 each:
>>> range(3,10,2)
[3, 5, 7, 9]
Python counts down if the third number is negative. You need to make the first number bigger than the second, though:
>>> range(13,10,-1)
[13, 12, 11]
You can iterate (take each value in order) through each of the numbers as range counts them:
>>> for i in range(3):
… print(i)
…
0
1
2
Because it’s a new code block, print(i) has four spaces before it.
This code has the same structure (it’s built the same) you saw in the while loop, although now there's no conditional. Instead, the for statement names a variable (in this case i). The variable takes the value of each number created by range(3).
The code block repeats for each of the numbers 0, 1, and 2 (although the code block in this case is only a single line of code — print(i)). You can give the variable any name, but it’s a throwaway variable with no meaning outside the loop, so something short is preferable. Certainly don't give it the same name as another variable or use a variable that is storing something important.
Be aware that on each loop iteration, the value of the dummy variable changes. That’s why the dummy variable should be just that — a throwaway that’s only used in the code block defined by the for loop. (When you’re really experienced, you can bend this rule to suit your needs.)
You can use a dummy variable to change the infinite while loop so it runs only enough times to fill the screen. Then it stops.
>>> my_message = "Hello World!"
>>> for i in range(300):
… print(my_message),
…
You should see something like Figure 2-3.
In this case you’d add NUMBER_OF_HELLOS = 300 earlier and change the range entry to be range(NUMBER_OF_HELLOS). This makes no difference in a three-line program, but it matters as your programs grow.
You might not think you’ll need to change these numbers, but you often do (for example, several times during the whole of your development). If they’re inlined as numbers everywhere (that is, not assigned to a variable and referenced through the variable) in your code, then you have to find and change each one. Plus, since it’s a number, it has none of the context that it would have if it was assigned to a variable with a meaningful name; it’s not always clear that it’s right to change it.
You might, for example, have another part of the code where you want to include 300 units of space. You decide that it should be 100 units of space instead, so you use search and replace to make every 300 a 100. If you’ve inlined these numbers, then you also wind up changing the 300 in the range and breaking your code.
In this project, you:
3.141.27.244