Files changed (15)
+Before we start writing computer games, we should learn some basic programming concepts first. These concepts are values, operators, expressions, and variables. We won't start programming in this chapter, but knowing these concepts and the names of things will make learning to program much easier. This is because most programming is built on only a few simple concepts combined together to make advanced programs.
+To open IDLE on Windows, click on Start, then Programs, then Python 3.1, then IDLE (Python GUI). With IDLE open, let's do some simple math with Python. The interactive shell can work just like a calculator. Type 2+2 into the shell and press the Enter key on your keyboard. (On some keyboards, this is the Return key.) As you can see in Figure 2-1, the computer should respond with the number 4; the sum of 2+2.
+As you can see, we can use the Python shell just like a calculator. This isn't a program by itself because we are just learning the basics right now. The + sign tells the computer to add the numbers 2 and 2. To subtract numbers use the - sign, and to multiply numbers use an asterisk (\*), like so:
+When used in this way, +, -, \*, and / are called operators because they tell the computer to perform the specified operation on the numbers surrounding them.
+In programming (and also in mathematics), whole numbers like 4, 0, and 99 are called integers. Numbers with fractions or decimal points (like 3.5 and 42.1 and 5.0) are not integers. In Python, the number 5 is an integer, but if we wrote it as 5.0 it would not be an integer. Numbers with a decimal point are called floating point numbers. In mathematics, 5.0 is still considered an integer and the same as the number 5, but in computer programming the computer considers any number with a decimal point as not an integer.
+Figure 2-2 is what the interactive shell in IDLE will look like after you type in the instructions above.
+These math problems are called expressions. Computers can solve millions of these problems in seconds. Expressions are made up of values (the numbers) connected by operators (the math signs). Let's learn exactly what values and operators are.
+As you can see with the last expression in the above example, you can put any amount of spaces in between the integers and these operators. (But be sure to always start at the very beginning of the line, with no spaces in front.)
+Numbers are a type of value. Integers are a type of number. But, even though integers are numbers, not all numbers are integers. (For example, fractions and numbers with decimal points like 2.5 are numbers that are not integers.)
+This is like how a cat is a type of pet, but not all pets are cats. Someone could have a pet dog or a pet hermit crab. An expression is made up of values (such as integers like 8 and 6) connected by an operator (such as the * multiplication sign). A single value by itself is also considered an expression.
+In the next chapter, we will learn about working with text in expressions. Python isn't limited to just numbers. It's more than just a fancy calculator!
+When a computer solves the expression 10 + 5 and gets the value 15, we say it has evaluated the expression. Evaluating an expression reduces the expression to a single value, just like solving a math problem reduces the problem to a single number: the answer.
+The expressions 10 + 5 and 10 + 3 + 2 have the same value, because they both evaluate to 15. Even single values are considered expressions: The expression 15 evaluates to the value 15.
+This error happened because 5 + is not an expression. Expressions have values connected by operators, but the + operator always expects to connect two things in Python. We have only given it one. This is why the error message appeared. A syntax error means that the computer does not understand the instruction you gave it because you typed it incorrectly. Python will always display an error message if you enter an instruction that it cannot understand.
+This may not seem important, but a lot of computer programming is not just telling the computer what to do, but also knowing exactly how to tell the computer to do it.
+Expressions can also contain other expressions. For example, in the expression 2 + 5 + 8, the 2 + 5 part is its own expression. Python evaluates 2 + 5 to 7, so the original expression becomes 7 + 8. Python then evaluates this expression to 15.
+Think of an expression as being a stack of pancakes. If you put two stacks of pancakes together, you still have a stack of pancakes. And a large stack of pancakes can be made up of smaller stacks of pancakes that were put together. Expressions can be combined together to form larger expressions in the same way. But no matter how big an expression is it also evaluates to a single answer, just like 2 + 5 + 8 evaluates to 15.
+When we program, we will often want to save the values that our expressions evaluate to so we can use them later in the program. We can store values in variables.
+Think of variables like a box that can hold values. You can store values inside variables with the = sign (called the assignment operator). For example, to store the value 15 in a variable named "spam", enter spam = 15 into the shell::
+You can think of the variable like a box with the value 15 inside of it (as shown in Figure 2-4). The variable name "spam" is the label on the box (so we can tell one variable from another) and the value stored in it is like a small note inside the box.
+When you press Enter you won't see anything in response, other than a blank line. Unless you see an error message, you can assume that the instruction has been executed successfully. The next >>> prompt will appear so that you can type in the next instruction.
+This instruction (called an assignment statement) creates the variable spam and stores the value 15 in it. Unlike expressions, statements are instructions that do not evaluate to any value, which is why there is no value displayed on the next line in the shell.
+It might be confusing to know which instructions are expressions and which are statements. Just remember that if the instruction evaluates to a single value, it's an expression. If the instruction does not, then it's a statement.
+An assignment statement is written as a variable, followed by the = equal sign, followed by an expression. The value that the expression evaluates to is stored inside the variable. The value 15 by itself is an expression. Expressions made up of a single value by itself are easy to evaluate. These expressions just evaluate to the value itself. For example, the expression 15 evaluates to 15!
+Remember, variables store values, not expressions. For example, if we had the statement, spam = 10 + 5, then the expression 10 + 5 would first be evaluated to 15 and then the value 15 would be stored in the variable, spam.
+The first time you store a value inside a variable by using an assignment statement, Python will create that variable. Each time after that, an assignment statement will only replace the value stored in the variable.
+Now let's see if we've created our variable properly. If we type spam into the shell by itself, we should see what value is stored inside the variable spam.
+And here's an interesting twist. If we now enter spam + 5 into the shell, we get the integer 20, like so.
+That may seem odd but it makes sense when we remember that we set the value of spam to 15. Because we've set the value of the variable spam to 15, writing spam + 5 is like writing the expression 15 + 5.
+If you try to use a variable before it has been created, Python will give you an error because no such variable would exist yet. This also happens if you mistype the name of the variable.
+We can change the value stored in a variable by entering another assignment statement. For example, try the following:
+The first time we enter spam + 5, the expression evaluates to 20, because we stored the value 15 inside the variable spam. But when we enter spam = 3, the value 15 is replaced, or overwritten, with the value 3. Now, when we enter spam + 5, the expression evaluates to 8 because the value of spam is now 3.
+To find out what the current value is inside a variable, just enter the variable name into the shell.
+Now here's something interesting. Because a variable is only a name for a value, we can write expressions with variables like this:
+When the variable spam has the integer value 15 stored in it, entering spam + spam is the same as entering 15 + 15, which evaluates to 30. And spam - spam is the same as 15 - 15, which evaluates to 0. The expressions above use the variable spam twice. You can use variables as many times as you want in expressions. Remember that Python will evaluate a variable name to the value that is stored inside that variable, each time the variable is used.
+The assignment statement spam = spam + 5 is like saying, "the new value of the spam variable will be the current value of spam plus five." Remember that the variable on the left side of the = sign will be assigned the value that the expression on the right side evaluates to. We can also keep increasing the value in spam by 5 several times:
+When we program we won't always want to be limited to only one variable. Often we'll need to use multiple variables.
+Without changing the value in our spam variable, let's try assigning a new value to the spam variable. Enter spam = fizz + eggs into the shell then enter spam into the shell to see the new value of spam. Can you guess what it will be?
+The value in spam is now 25 because when we add fizz and eggs we are adding the values stored inside fizz and eggs.
+Changing the value stored inside a variable is easy. Just perform another assignment statement with the same variable. Look what happens when you enter the following code into the interactive shell:
+Initially, the spam variable had the integer 42 placed inside of it. This is why the first print(spam) prints out 42. But when we execute spam = 'Hello', the 42 value is tossed out of the variable and forgotten as the new 'Hello' string value is placed inside the spam variable.
+Replacing the value in a variable with a new value is called overwriting the value. It is important to know that the old value is permanently forgotten. If you want to remember this value so you can use it later in your program, store it in a different variable before overwriting the value:
+In the above example, before overwriting the value in spam, we copy that value to a variable named oldSpam. At that point, both spam and oldSpam store the value 42. On the next line, the string 'Hello' is stored in spam but oldSpam is left untouched.
+In this chapter you learned the basics about writing Python instructions. Python needs you to tell it exactly what to do in a strict way, because computers don't have common sense and only understand very simple instructions. You have learned that Python can evaluate expressions (that is, reduce the expression to a single value), and that expressions are values (such as 2 or 5) combined with operators (such as + or -). You have also learned that you can store values inside of variables so that your program can remember them in order to use them later on.
+That's enough of integers and math for now. Python is more than just a calculator. Now let's see what Python can do with text. In this chapter, we will learn how to store text in variables, combine text together, and display them on the screen. Many of our programs will use text to display our games to the player, and the player will enter text into our programs through the keyboard. We will also make our first program, which greets the user with the text, "Hello World!" and asks for the user's name.
+In Python, we work with little chunks of text called strings. We can store string values inside variables just like we can store number values inside variables. When we type strings, we put them in between two single quotes ('), like this:
+The single quotes are there only to tell the computer where the string begins and ends (and are not part of the string value).
+Now, if you type spam into the shell, you should see the contents of the spam variable (the 'hello' string.) This is because Python will evaluate a variable to the value stored inside the variable (in this case, the string 'Hello').
+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:
+As we did with numerical values in the previous chapter, we can also combine string values together with operators to make expressions.
+You can add one string to the end of another by using the + operator, which is called string concatenation. Try entering 'Hello' + 'World!' into the shell:
+To keep the strings separate, put a space at the end of the 'Hello' string, before the single quote, like this:
+The + operator works differently on strings and integers because they are different data types. All values have a data type. The data type of the value 'Hello' is a string. The data type of the value 5 is an integer. The data type of the data that tells us (and the computer) what kind of data the value is.
+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!
+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.
+Click on the File menu at the top of the Python Shell window, and select New Window. A new blank window will appear for us to type our program in. This window is the file editor.
+Figure 3-2: The bottom right of the file editor window tells you where the cursor is. The cursor is currently on line 12.
+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.
+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.
+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!)
+IMPORTANT NOTE! 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 http://python.org/download/releases/3.1.1/ and install this version.::
+ If you get errors after typing this code in, compare it to the book's code with the online diff tool at http://inventwithpython.com/diff or email the author at email@example.com
+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:
+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 Save As. The Save As window should open. Enter hello.py in the File Name box then press Save. (See Figure 3-4.)
+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.
+A video tutorial of how to use the file editor is available from this book's website at http://inventwithpython.com/videos/.
+...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.
+To load a saved program, choose File > Open. Do that now, and in the window that appears choose hello.py and press the Open button. Your saved hello.py program should open in the File Editor window.
+Now it's time to run our program. From the File menu, choose Run > Run Module 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.
+Now, when you push Enter, the program should greet you (the user) 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.)
+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.
+We call the program's following of instructions step-by-step the flow of execution, or just the execution for short.
+Now let's look at our program one line at a time to see what it's doing, beginning with line number 1.
+This line is called a comment. Any text following a # sign (called the pound sign) 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.
+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.
+A function 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 print() function displays text on the screen, but you don't need to know how it does this.)
+A function call is a piece of code that tells our program to run the code inside a function. For example, your program can call the print() function whenever you want to display a string on the screen. The print() function takes the string you type in between the parentheses as input and displays the text on the screen. Because we want to display Hello world! on the screen, we type the print function name, followed by an opening parenthesis, followed by the 'Hello world!' string and a closing parenthesis.
+This line is a call to the print function, usually written as print() (with the string to be printed going inside the parentheses).
+We add parentheses to the end of function names to make it clear that we're referring to a function named print(), not a variable named print. The parentheses at the end of the function let us know we are talking about a function, much like the quotes around the number '42' tell us that we are talking about the string '42' and not the integer 42.
+This line has an assignment statement with a variable (myName) and a function call (input()). When input() 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.
+Like expressions, function calls evaluate to a single value. The value that the function call evaluates to is called the return value. (In fact, we can also use the word "returns" to mean the same thing as "evaluates".) In this case, the return value of the input() function is the string that the user typed in-their name. If the user typed in Albert, the input() function call evaluates to the string 'Albert'.
+The function named input() does not need any input (unlike the print() function), which is why there is nothing in between the parentheses.::
+On the last line we have a print() function again. This time, we use the plus operator (+) to concatenate the string 'It is good to meet you, ' and the string stored in the myName variable, which is the name that our user input into the program. This is how we get the program to greet us by name.
+Once the program executes the last line, it stops. At this point it has terminated or exited and all of the variables are forgotten by the computer, including the string we stored in myName. If you try running the program again with a different name, like Carolyn, it will think that's your name.::
+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.
+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:
+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 name, we could have called this variable abrahamLincoln or nAmE. The computer will run the program the same (as long as you consistently use abrahamLincoln or nAmE).
+Variable names (as well as everything else in Python) are case-sensitive. Case-sensitive means the same variable name in a different case is considered to be an entirely separate variable name. So spam, SPAM, Spam, and sPAM are considered to be four different variables in Python. They each can contain their own separate values.
+It's a bad idea to have differently-cased variables in your program. If you stored your first name in the variable name and your last name in the variable NAME, it would be very confusing when you read your code weeks after you first wrote it. Did name mean first and NAME mean last, or the other way around?
+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 bug. 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.
+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 whatIHadForBreakfastThisMorning is much easier to read than whatihadforbreakfastthismorning. This is a convention (that is, an optional but standard way of doing things) in Python programming. (Although even better would be something simple, like todaysBreakfast. Capitalizing the first letter of each word in variable names makes the program more readable.
+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 input() function. And the computer will display text on the screen when the print() function is executed.
+Strings are just a different data type that we can use in our programs. We can use the + operator to concatenate strings together. Using the + operator to concatenate two strings together to form a new string is just like using the + operator to add two integers to form a new integer (the sum).