-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathchapter3.html
301 lines (193 loc) · 22.2 KB
/
chapter3.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-5459430-3");
pageTracker._trackPageview();
} catch(err) {}</script>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>IYOCGwP, Chapter 3 - Strings, and Your First Program</title>
<link rel="stylesheet" href="inventbook.css" type="text/css" media="all" />
</head>
<body>
<table border='0' width='100%'><tr><td><a href='chapter2.html'>Go to Chapter 2 - The Interactive Shell</a></td><td align='right'><a href='chapter4.html'>Go to Chapter 4 - Guess the Number</a></td></tr></table>
<div style='height: 310px;'><a href='http://www.amazon.com/Invent-Your-Computer-Games-Python/dp/0982106017/'><img src='images/buyad.png' align='right'></a></div>
<div style='height: 350px;'><img src='images/chap3.png'></div>
<div class='inthischapter'><h3 id="TopicsCoveredInThisChapter">Topics Covered In This Chapter:</h3>
<ul>
<ul>
<li>Fluxo de execução</li>
<li>Strings</li>
<li>Concatenação de Strings</li>
<li>Tipos de dados (como strings ou inteiros)</li>
<li>Usando o IDLE para escrever código</li>
<li>Salvando e executando programas com o IDLE</li>
<li>A função <span class='m'>print()</span></li>
<li>A função <span class='m'>input()</span></li>
<li>Comentários</li>
<!-- TODO: tradução para capitalizing -->
<li>**Capitalizing** variáveis</li>
<!-- TODO: tradução para case-sensitive -->
<li>Diferenças entre Maiúsculas e Minúsculas</li>
</ul></div>
<p>Chega de inteiros e matemática por enquanto. Python é muito mais do que uma calculadora. Agora, vamos ver o que Python pode fazer com texto. Neste capítulo, iremos aprender como armazenar texto em variáveis, combinar textos e mostrá-los na tela. Muitos de nossos programas utilizarão texto para apresentar nossos jogos ao jogador, que por sua vez digitará texto para nossos programas através do teclado. Também criaremos nosso primeiro programa, que saúda o usuário com o texto "Alô Mundo!" e solicita ao usuário o seu nome.</p>
<h2 id="Strings">Strings</h2>
<p>Em Python, trabalhamos com pequenos trechos de texto chamados de <span class='term'>strings</span>. Nós podemos armazenar strings em variáveis assim como podemos armazenar números dentro de variáveis. Quando digitamos strings, colocamos elas entre duas aspas (') simples, assim:
<div class='sourceblurb'>
>>> spam = 'alô'<br />
>>><br />
</div>
<p>As aspas simples estão ali somente para informar ao computador onde a string começa e onde ela termina (e não são parte do conteúdo da string em si).</p>
<p>Now, if you type <span class='m'>spam</span> into the shell, you should see the contents of the <span class='m'>spam</span> variable (the <span class='m'>'hello'</span> string.) This is because Python will evaluate a variable to the value stored inside the variable (in this case, the string <span class='m'>'Hello'</span>).</p>
<p>Agora, se você digitar <span class='m'>spam</span> no console interativo, você deve ver o conteúdo da variável ``spam`` (a string ``'hello'``). Isso porque Python irá interpretar a variável como o valor armazenado dentro dela (neste caso, a string ``'hello'``).
<div class='sourceblurb'>
>>> spam = 'hello'<br />
>>> spam<br />
'hello'<br />
>>><br />
</div>
<p>Strings can have almost any keyboard character in them. (Strings can't have single quotes inside of them without using escape characters. Escape characters are described later.) These are all examples of strings:</p>
<div class='sourceblurb'>
'hello'<br />
'Hi there!'<br />
'KITTENS'<br />
'7 apples, 14 oranges, 3 lemons'<br />
'Anything not pertaining to elephants is irrelephant.'<br />
'A long time ago in a galaxy far, far away...'<br />
'O*&#wY%*&OCfsdYO*&gfC%YO*&%3yc8r2'<br />
</div>
<p>As we did with numerical values in the previous chapter, we can also combine string values together with operators to make expressions.</p>
<h2 id="StringConcatenation">String Concatenation</h2>
<p>You can add one string to the end of another by using the <span class='m'>+</span> operator, which is called string concatenation. Try entering <span class='m'>'Hello' + 'World!'</span> into the shell:</p>
<div class='sourceblurb'>
>>> 'Hello' + 'World!'<br />
'HelloWorld!'<br />
>>><br />
</div>
<p>To keep the strings separate, put a space at the end of the <span class='m'>'Hello'</span> string, before the single quote, like this:</p>
<div class='sourceblurb'>
>>> 'Hello ' + 'World!'<br />
'Hello World!'<br />
>>><br />
</div>
<p>The <span class='m'>+</span> operator works differently on strings and integers because they are different <span class='term'>data types</span>. All values have a data type. The data type of the value <span class='m'>'Hello'</span> is a string. The data type of the value <span class='m'>5</span> is an integer. The data type of the data that tells us (and the computer) what kind of data the value is.</p>
<h2 id="WritingProgramsinIDLEsFileEditor">Writing Programs in IDLE's File Editor</h2>
<p>Until now we have been typing instructions one at a time into the interactive shell. When we write programs though, we type in several instructions and have them run all at once. Let's write our first program!</p>
<p>The name of the program that provides the interactive shell is called IDLE, the Interactive DeveLopement Environment. IDLE also has another part called the file editor.</p>
<p>Click on the <span class='menuname'>File</span> menu at the top of the Python Shell window, and select <span class='menuname'>New Window</span>. A new blank window will appear for us to type our program in. This window is the <span class='term'>file editor</span>.</p>
<p class='centeredImageP'><img src='images/3-1.png' alt='' class='centeredImage' /><br />
Figure 3-1: The file editor window.</p>
<h2 class='pagebreaker' id="HelloWorld">Hello World!</h2>
<table class='floatTable'><tr><td class='floatTable'>
<p style='float: right;' class='centeredImageP'><img src='images/3-2.png' alt='' class='centeredImage' /><br />
Figure 3-2: The bottom right of the file<br />editor window tells you where the cursor<br />is. The cursor is currently on line 12.</p>
<p>A tradition for programmers learning a new language is to make their first program display the text "Hello world!" on the screen. We'll create our own Hello World program now.</p>
<p>When you enter your program, don't enter the numbers at the left side of the code. They're there so we can refer to each line by number in our explanation. If you look at the bottom-right corner of the file editor window, it will tell you which line the cursor is currently on.</p>
<p>Enter the following text into the new file editor window. We call this text the program's source code because it contains the instructions that Python will follow to determine exactly how the program should behave. (Remember, don't type in the line numbers!)</p>
<p><b>IMPORTANT NOTE!</b> The following program should be run by the Python 3 interpreter, not the Python 2.6 (or any other 2.x version). Be sure that you have the correct version of Python installed. (If you already have Python 2 installed, you can have Python 3 installed at the same time.) To download Python 3, go to <a href='http://python.org/download/releases/3.1.1/'>http://python.org/download/releases/3.1.1/</a> and install this version.</p>
</td></tr></table>
<div class='sourcecode'><span class='sourcecodeHeader'>hello.py</span><br /><span class='sourcecodeSubHeader'>This code can be downloaded from <a href='http://inventwithpython.com/hello.py'>http://inventwithpython.com/hello.py</a><br />If you get errors after typing this code in, compare it to the book's code with the online diff tool at <a href='http://inventwithpython.com/diff'>http://inventwithpython.com/diff</a> or email the author at <a href="mailto:[email protected]">[email protected]</a></span><br /><ol start='1'>
<li><span class='comment'># This program says hello and asks for my name.</span></li>
<li>print('Hello world!')</li>
<li>print('What is your name?')</li>
<li>myName = input()</li>
<li>print('It is good to meet you, ' + myName)</li>
</ol></div>
<p>The IDLE program will give different types of instructions different colors. After you are done typing this code in, the window should look like this:</p>
<p class='centeredImageP'><img src='images/3-3.png' alt='' class='centeredImage' /><br />
Figure 3-3: The file editor window will look like this after you type in the code.</p>
<h3 id="SavingYourProgram">Saving Your Program</h3>
<table class='floatTable'><tr><td class='floatTable'>
<p style='float: right;' class='centeredImageP'><img src='images/3-4.png' alt='' class='centeredImage' /><br />
Figure 3-4: Saving the program.</p>
<p>Once you've entered your source code, save it so that you won't have to retype it each time we start IDLE. To do so, choose the File menu at the top of the File Editor window, and then click on <span class='menuname'>Save As</span>. The Save As window should open. Enter <span class='filename'>hello.py</span> in the File Name box then press <span class='menuname'>Save</span>. (See Figure 3-4.)</p>
<p>You should save your programs every once in a while as you type them. That way, if the computer crashes or you accidentally exit from IDLE, only the typing you've done since your last save will be lost. Press Ctrl-S to save your file quickly, without using the mouse at all.</p>
</td></tr></table>
<p>A video tutorial of how to use the file editor is available from this book's website at <a href='http://inventwithpython.com/videos/'>http://inventwithpython.com/videos/</a>.</p>
<p>If you get an error that looks like this:</p>
<div class='sourceblurb'>
Hello world!<br />
What is your name?<br />
Albert<br />
<br />
Traceback (most recent call last):<br />
File "C:/Python26/test1.py", line 4, in <module><br />
myName = input()<br />
File "<string>", line 1, in <module><br />
NameError: name 'Albert' is not defined<br />
</div>
<p>...then this means you are running the program with Python 2, instead of Python 3. You can either install Python 3, or convert the source code in this book to Python 2. Appendix A lists the differences between Python 2 and 3 that you will need for this book.</p>
<h3 id="OpeningTheProgramsYouveSaved">Opening The Programs You've Saved</h3>
<p>To load a saved program, choose <span class='menuname'>File > Open</span>. Do that now, and in the window that appears choose <span class='filename'>hello.py</span> and press the <span class='menuname'>Open</span> button. Your saved <span class='filename'>hello.py</span> program should open in the File Editor window.</p>
<p>Now it's time to run our program. From the File menu, choose <span class='menuname'>Run > Run Module</span> or just press the F5 key on your keyboard. Your program should run in the shell window that appeared when you first started IDLE. Remember, you have to press F5 from the file editor's window, not the interactive shell's window.</p>
<p>When your program asks for your name, go ahead and enter it as shown in Figure 3-5:</p>
<p class='centeredImageP'><img src='images/3-5.png' alt='' class='centeredImage' /><br />
Figure 3-5: What the interactive shell looks like when running the "Hello World" program.</p>
<p>Now, when you push Enter, the program should greet you (the <span class='term'>user</span>) by name. Congratulations! You've written your first program. You are now a beginning computer programmer. (You can run this program again if you like by pressing F5 again.)</p>
<h2 id="HowtheHelloWorldProgramWorks">How the "Hello World" Program Works</h2>
<p>How does this program work? Well, each line that we entered is an instruction to the computer that is interpreted by Python in a way that the computer will understand. A computer program is a lot like a recipe. Do the first step first, then the second, and so on until you reach the end. Each instruction is followed in sequence, beginning from the very top of the program and working down the list of instructions. After the program executes the first line of instructions, it moves on and executes the second line, then the third, and so on.</p>
<p>We call the program's following of instructions step-by-step the <span class='term'>flow of execution</span>, or just the <span class='term'>execution</span> for short.</p>
<p>Now let's look at our program one line at a time to see what it's doing, beginning with line number 1.</p>
<h3 id="Comments">Comments</h3>
<div class='sourcecode'><ol start='1'>
<li><span class='comment'># This program says hello and asks for my name.</span></li>
</ol></div>
<p>This line is called a <span class='term'>comment</span>. Any text following a <span class='m'>#</span> sign (called the <span class='term'>pound sign</span>) is a comment. Comments are not for the computer, but for you, the programmer. The computer ignores them. They're used to remind you of what the program does or to tell others who might look at your code what it is that your code is trying to do.</p>
<p>Programmers usually put a comment at the top of their code to give their program a title. The IDLE program displays comments in red to help them stand out.</p>
<h3 id="Functions">Functions</h3>
<p>A <span class='term'>function</span> is kind of like a mini-program inside your program. It contains lines of code that are executed from top to bottom. Python provides some built-in functions that we can use. The great thing about functions is that we only need to know what the function does, but not how it does it. (You need to know that the <span class='m'>print()</span> function displays text on the screen, but you don't need to know how it does this.)</p>
<p>A <span class='term'>function call</span> is a piece of code that tells our program to run the code inside a function. For example, your program can call the <span class='m'>print()</span> function whenever you want to display a string on the screen. The <span class='m'>print()</span> function takes the string you type in between the parentheses as input and displays the text on the screen. Because we want to display <span class='m'>Hello world!</span> on the screen, we type the <span class='m'>print</span> function name, followed by an opening parenthesis, followed by the <span class='m'>'Hello world!'</span> string and a closing parenthesis.</p>
<h3 id="TheprintFunction">The <span class='m'>print()</span> Function</h3>
<div class='sourcecode'><ol start='2'>
<li>print('Hello world!')</li>
<li>print('What is your name?')</li>
</ol></div>
<p>This line is a call to the <span class='term'>print</span> function, usually written as <span class='m'>print()</span> (with the string to be printed going inside the parentheses).</p>
<p>We add parentheses to the end of function names to make it clear that we're referring to a function named <span class='m'>print()</span>, not a variable named <span class='m'>print</span>. The parentheses at the end of the function let us know we are talking about a function, much like the quotes around the number <span class='m'>'42'</span> tell us that we are talking about the string <span class='m'>'42'</span> and not the integer <span class='m'>42</span>. </p>
<p>Line 3 is another <span class='m'>print()</span> function call. This time, the program displays "What is your name?"</p>
<h3 id="TheinputFunction">The <span class='m'>input()</span> Function</h3>
<div class='sourcecode'><ol start='4'>
<li>myName = input()</li>
</ol></div>
<p>This line has an assignment statement with a variable (<span class='m'>myName</span>) and a function call (<span class='m'>input()</span>). When <span class='m'>input()</span> is called, the program waits for input; for the user to enter text. The text string that the user enters (your name) becomes the function's output value.</p>
<p>Like expressions, function calls evaluate to a single value. The value that the function call evaluates to is called the <span class='term'>return value</span>. (In fact, we can also use the word "returns" to mean the same thing as "evaluates".) In this case, the return value of the <span class='m'>input()</span> function is the string that the user typed in-their name. If the user typed in Albert, the <span class='m'>input()</span> function call evaluates to the string <span class='m'>'Albert'</span>.</p>
<p>The function named <span class='m'>input()</span> does not need any input (unlike the <span class='m'>print()</span> function), which is why there is nothing in between the parentheses.</p>
<div class='sourcecode'><ol start='5'>
<li>print('It is good to meet you, ' + myName)</li>
</ol></div>
<p>On the last line we have a <span class='m'>print()</span> function again. This time, we use the plus operator (<span class='m'>+</span>) to concatenate the string <span class='m'>'It is good to meet you, '</span> and the string stored in the <span class='m'>myName</span> variable, which is the name that our user input into the program. This is how we get the program to greet us by name.</p>
<h3 id="EndingtheProgram">Ending the Program</h3>
<p>Once the program executes the last line, it stops. At this point it has <span class='term'>terminated</span> or <span class='term'>exited</span> and all of the variables are forgotten by the computer, including the string we stored in <span class='m'>myName</span>. If you try running the program again with a different name, like Carolyn, it will think that's your name.</p>
<div class='sourceblurb'>
Hello world!<br />
What is your name?<br />
Carolyn<br />
It is good to meet you, Carolyn<br />
</div>
<p>Remember, the computer only does exactly what you program it to do. In this, our first program, it is programmed to ask you for your name, let you type in a string, and then say hello and display the string you typed.</p>
<p>But computers are dumb. The program doesn't care if you type in your name, someone else's name, or just something dumb. You can type in anything you want and the computer will treat it the same way:</p>
<div class='sourceblurb'>
Hello world!<br />
What is your name?<br />
poop<br />
It is good to meet you, poop<br />
</div>
<h2>Variable Names</h2>
<p>The computer doesn't care what you name your variables, but you should. Giving variables names that reflect what type of data they contain makes it easier to understand what a program does. Instead of <span class='m'>name</span>, we could have called this variable <span class='m'>abrahamLincoln</span> or <span class='m'>nAmE</span>. The computer will run the program the same (as long as you consistently use <span class='m'>abrahamLincoln</span> or <span class='m'>nAmE</span>).</p>
<p>Variable names (as well as everything else in Python) are case-sensitive. <span class='term'>Case-sensitive</span> means the same variable name in a different case is considered to be an entirely separate variable name. So <span class='m'>spam</span>, <span class='m'>SPAM</span>, <span class='m'>Spam</span>, and <span class='m'>sPAM</span> are considered to be four different variables in Python. They each can contain their own separate values.</p>
<p>It's a bad idea to have differently-cased variables in your program. If you stored your first name in the variable <span class='m'>name</span> and your last name in the variable <span class='m'>NAME</span>, it would be very confusing when you read your code weeks after you first wrote it. Did <span class='m'>name</span> mean first and <span class='m'>NAME</span> mean last, or the other way around?</p>
<p>If you accidentally switch the name and NAME variables, then your program will still run (that is, it won't have any syntax errors) but it will run incorrectly. This type of flaw in your code is called a <span class='term'>bug</span>. It is very common to accidentally make bugs in your programs while you write them. This is why it is important that the variable names you choose make sense.</p>
<p>It also helps to capitalize variable names if they include more than one word. If you store a string of what you had for breakfast in a variable, the variable name <span class='m'>whatIHadForBreakfastThisMorning</span> is much easier to read than <span class='m'>whatihadforbreakfastthismorning</span>. This is a <span class='term'>convention</span> (that is, an optional but standard way of doing things) in Python programming. (Although even better would be something simple, like <span class='m'>todaysBreakfast</span>. Capitalizing the first letter of each word in variable names makes the program more readable.</p>
<h2 id="Summary">Summary</h2>
<p>Now that we have learned how to deal with text, we can start making programs that the user can run and interact with. This is important because text is the main way the user and the computer will communicate with each other. The player will enter text to the program through the keyboard with the <span class='m'>input()</span> function. And the computer will display text on the screen when the <span class='m'>print()</span> function is executed.</p>
<p>Strings are just a different data type that we can use in our programs. We can use the <span class='m'>+</span> operator to concatenate strings together. Using the <span class='m'>+</span> operator to concatenate two strings together to form a new string is just like using the <span class='m'>+</span> operator to add two integers to form a new integer (the sum).</p>
<p>In the next chapter, we will learn more about variables so that our program will remember the text and numbers that the player enters into the program. Once we have learned how to use text, numbers, and variables, we will be ready to start creating games.</p>
<table border='0' width='100%'><tr><td><a href='chapter2.html'>Go to Chapter 2 - The Interactive Shell</a></td><td align='right'><a href='chapter4.html'>Go to Chapter 4 - Guess the Number</a></td></tr></table>
<div style='height: 310px;'><a href='http://www.amazon.com/Invent-Your-Computer-Games-Python/dp/0982106017/'><img src='images/buyad.png' align='right'></a></div>
</body>
</html>