04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 1 ■ INSTANT HACKING: THE BASICS 23<br />

It’s always a good idea to make your code readable on its own as well, even without the<br />

comments. Luckily, Python is an excellent language for writing readable programs.<br />

Strings<br />

Now what was all that raw_input and "Hello, " + name + "!" stuff about? Let’s tackle the<br />

"Hello" part first and leave raw_input for later.<br />

The first program in this chapter was simply<br />

print "Hello, world!"<br />

It is customary to begin with a program like this in programming tutorials—the problem is that I<br />

haven’t really explained how it works yet. Well, you know the basics of the print statement (I’ll have<br />

more to say about that later), but what is "Hello, world!"? It’s called a string (as in “a string of characters”).<br />

Strings are found in almost every useful, real-world Python program and have many uses,<br />

the main one being to represent a bit of text, such as the exclamation “Hello, world!”<br />

Single-Quoted Strings and Escaping Quotes<br />

Strings are values, just like numbers are:<br />

>>> "Hello, world!"<br />

'Hello, world!'<br />

There is one thing that may be a bit surprising about this example, though: When Python<br />

printed out our string, it used single quotes, whereas we used double quotes. What’s the difference?<br />

Actually, there is no difference:<br />

>>> 'Hello, world!'<br />

'Hello, world!'<br />

Here, too, we use single quotes, and the result is the same. So why allow both? Because in some<br />

cases it may be useful:<br />

>>> "Let's go!"<br />

"Let's go!"<br />

>>> '"Hello, world!" she said'<br />

'"Hello, world!" she said'<br />

In the preceding code, the first string contains a single quote (or apostrophe, as we should<br />

perhaps call it in this context), and therefore we can’t use single quotes to enclose the string.<br />

If we did, the interpreter would complain (and rightly so):<br />

>>> 'Let's go!'<br />

SyntaxError: invalid syntax<br />

Here, the string is 'Let', and Python doesn’t quite know what to do with the following s (or the<br />

rest of the line, for that matter).<br />

In the second string, we use double quotes as part of our sentence. Therefore, we have to<br />

use single quotes to enclose our string, for the same reasons as stated previously. Or, actually

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!