Invent Your Own Computer Games with Python 2nd Edition Al Sweigart
Copyright © 2008, 2009, 2010 by Albert Sweigart Some Rights Reserved. "Invent Your Own Computer Games with Python" ("Invent with Python") is licensed under a Creative Commons Attribution-NoncommercialShare Alike 3.0 United States License. You are free: To Share — to copy, distribute, display, and perform the work To Remix — to make derivative works Under the following conditions: Attribution — You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). (Visibly include the title and author's name in any excerpts of this work.) Noncommercial — You may not use this work for commercial purposes. Share Alike — If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one. This summary is located here: http://creativecommons.org/licenses/by-nc-sa/3.0/us/ Your fair use and other rights are in no way affected by the above. There is a human-readable summary of the Legal Code (the full license), located here: http://creativecommons.org/licenses/by-nc-sa/3.0/us/legalcode Book Version 13 ISBN 978-0-9821060-1-3 2nd Edition
A Note to Parents and Fellow Programmers Thank your for reading this book. My motivation for writing this book comes from a gap I saw in today's literature for kids interested in learning to program. I started programming when I was 9 years old in the BASIC language with a book similar to this one. During the course of writing this, I've realized how a modern language like Python has made programming far easier and versatile for a new generation of programmers. Python has a gentle learning curve while still being a serious language that is used by programmers professionally. The current crop of programming books for kids that I've seen fell into two categories. First, books that did not teach programming so much as "game creation software" or a dumbed-down languages to make programming "easy" (to the point that it is no longer programming). Or second, they taught programming like a mathematics textbook: all principles and concepts with little application given to the reader. This book takes a different approach: show the source code for games right up front and explain programming principles from the examples. I have also made this book available under the Creative Commons license, which allows you to make copies and distribute this book (or excerpts) with my full permission, as long as attribution to me is left intact and it is used for noncommercial purposes. (See the copyright page.) I want to make this book a gift to a world that has given me so much. Thank you again for reading this book, and feel free to email me any questions or comments. Al Sweigart [email protected] The full text of this book is available in HTML or PDF format at: http://inventwithpython.com
Dinosaur Comics reproduced with permission Thanks Ryan! Who is this book for? Programming isn't hard. But it is hard to find learning materials that teach you to do interesting things with programming. Other computer books go over many topics that most newbie coders don't need. This book will teach you how to program your own computer games. You will learn a useful skill and have fun games to show for it! This book is for: Complete beginners who wants to teach themselves computer programming, even if they have no previous experience programming. Kids and teenagers who want to learn computer programming by creating games. Kids as young as 9 or 10 years old should be able to follow along. Adults and teachers who wish to teach others programming. Anyone, young or old, who wants to learn how to program by learning a professional programming language.
Table of Contents Source Code Listing hello.py 21 guess.py 30 jokes.py 51 dragon.py 58 buggy.py 83 coinFlips.py 87 hangman.py 103 tictactoe.py 150 truefalsefizz.py 172 bagels.py 184 sonar.py 213 cipher.py 244 reversi.py 261 aisim1.py 292 aisim2.py 294 aisim3.py 299 pygameHelloWorld.py 309 animation.py 324 collisionDetection.py 338 pygameInput.py 348 spritesAndSounds.py 360 dodger.py 371 1 Installing Python 1 Downloading and Installing Python 2 Starting Python 4 How to Use This Book 4 The Featured Programs 5 Line Numbers and Spaces 5 Summary 7 2 The Interactive Shell 8 Some Simple Math Stuff 8 Evaluating Expressions 11 Storing Values in Variables 12
Using More Than One Variable 15 Summary 16 3 Strings, and Your First Program 18 Strings 18 String Concatenation 19 Writing Programs in IDLE's File Editor 20 Hello World! 20 How the "Hello World" Program Works 23 Summary 26 4 Guess the Number 28 The "Guess the Number" Game 28 Sample Run of "Guess the Number" 29 Guess the Number's Source Code 29 The import Statement 31 The random.randint() Function 32 Passing Arguments to Functions 34 Blocks 36 The Boolean Data Type 37 Comparison Operators 37 Conditions 38 Experiment with Booleans, Comparison Operators, and Conditions 38 Looping with While Statements 41 The Player Guesses 41 if Statements 44 Leaving Loops Early with the break Statement 45 Check if the Player Won 46 Summary: What Exactly is Programming? 47 A Web Page for Program Tracing 48 5 Jokes 50 Make the Most of print() 50 Sample Run of Jokes 50 Joke's Source Code 51 Escape Characters 52
Quotes and Double Quotes 53 The end Keyword Argument 54 Summary 55 6 Dragon Realm 56 Introducing Functions 56 Sample Run of Dragon Realm 57 Dragon Realm's Source Code 57 def Statements 60 Boolean Operators 61 Return Values 65 Variable Scope 65 Parameters 68 Where to Put Function Definitions 70 Displaying the Game Results 71 The Colon : 73 Where the Program Really Begins 73 Designing the Program 75 Summary 76 7 Using the Debugger 77 Bugs! 77 Starting the Debugger 78 Stepping 80 The Go and Quit Buttons 81 Stepping Over and Stepping Out 81 Find the Bug 83 Break Points 86 Summary 88 8 Flow Charts 89 How to Play "Hangman" 89 Sample Run of "Hangman" 89 ASCII Art 91 Designing a Program with a Flowchart 92 Creating the Flow Chart 93
Summary: The Importance of Planning Out the Game 100 9 Hangman 102 Hangman's Source Code 103 Multi-line Strings 107 Constant Variables 108 Lists 108 Changing the Values of List Items with Index Assignment 110 List Concatenation 110 The in Operator 111 Removing Items from Lists with del Statements 112 Lists of Lists 113 Methods 114 The reverse() and append() List Methods 115 The Difference Between Methods and Functions 116 The split() Function 116 The range() and list() Functions 120 for Loops 121 elif ("Else If") Statements 127 Review of the Functions We Defined 131 Making New Changes to the Hangman Program 132 Dictionaries 139 Sets of Words for Hangman 142 The random.choice() Function 143 Multiple Assignment 145 Summary 147 10 Tic Tac Toe 148 Sample Run of Tic Tac Toe 149 Source Code of Tic Tac Toe 150 Designing the Program 154 Game AI 156 List References 162 Short-Circuit Evaluation 170 The None Value 175
Summary: Creating Game-Playing Artificial Intelligences 182 11 Bagels 183 Sample Run 184 Bagel's Source Code 184 Designing the Program 186 The random.shuffle() Function 188 Augmented Assignment Operators 190 The sort() List Method 192 The join() String Method 192 String Interpolation 194 Summary: Getting Good at Bagels 198 12 Cartesian Coordinates 200 Grids and Cartesian Coordinates 201 Negative Numbers 202 Math Tricks 204 Absolute Values and the abs() Function 206 Coordinate System of a Computer Monitor 207 Summary: Using this Math in Games 208 13 Sonar Treasure Hunt 209 Sample Run 210 Sonar's Source Code 213 Designing the Program 218 The remove() List Method 229 Summary: Review of our Sonar Game 238 14 Caesar Cipher 239 About Cryptography 239 The Caesar Cipher 240 ASCII, and Using Numbers for Letters 241 The chr() and ord() Functions 242 Sample Run of Caesar Cipher 243 Caesar Cipher's Source Code 244 The isalpha() String Method 247 The isupper() and islower() String Methods 248
Brute Force 251 Summary: Reviewing Our Caesar Cipher Program 253 15 Reversi 256 How to Play Reversi 255 Sample Run 257 Reversi's Source Code 260 The bool() Function 276 Summary: Reviewing the Reversi Game 290 16 AI Simulation 291 "Computer vs. Computer" Games 291 AISim1.py Source Code 292 AISim2.py Source Code 294 Percentages 296 The round() Function 297 Comparing Different AI Algorithms 299 AISim3.py Source Code 299 Learning New Things by Running Simulation Experiments 305 17 Graphics and Animation 306 Installing Pygame 307 Hello World in Pygame 308 Hello World's Source Code 308 Importing the Pygame Module 311 Variables Store References to Objects 313 Colors in Pygame 313 Fonts, and the pygame.font.SysFont() Function 315 Attributes 316 Constructor Functions and the type() function. 317 The pygame.PixelArray Data Type 321 Events and the Game Loop 322 Animation 324 The Animation Program's Source Code 324 Some Small Modifications 335 Summary: Pygame Programming 335
18 Collision Detection and Input 337 The Collision Detection Program's Source Code 337 The Collision Detection Function 341 The pygame.time.Clock Object and tick() Method 344 The Keyboard Input Program's Source Code 348 The colliderect() Method 356 Summary: Collision Detection and Pygame Input 356 19 Sound and Images 358 Image and Sound Files 360 Sprites and Sounds Program 360 The Sprites and Sounds Program's Source Code 360 Setting Up the Window and the Data Structure 364 The pygame.transform.scale() Function 364 Summary: Games with Graphics and Sounds 368 20 Dodger 369 Review of the Basic Pygame Data Types 370 Dodger's Source Code 371 Implementing the Cheat Codes 392 Modifying the Dodger Game 397 Summary: Creating Your Own Games 397 Appendix A Differences Between Python 2 and 3 399 Appendix B Statements, Functions, and Methods Reference 403 Appendix C Running Python Programs without Python Installed 404 Appendix D Common Error Messages in Python 407 Glossary 411 About the Author 421
Topics Covered In This Chapter: Downloading and installing the Python interpreter. Using IDLE's interactive shell to run instructions. How to use this book. The book's website at http://inventwithpython.com Hello! This is a book that will teach you how to program by showing you how to create computer games. Once you learn how the games in this book work, you'll be able to create your own games. All you'll need is a computer, some software called the Python Interpreter, and this book. The software you'll need is free and you can download it from the Internet. When I was a kid, I found a book like this that taught me how to write my first programs and games. It was fun and easy. Now as an adult, I still have fun programming computers, and I get paid for it. But even if you don't become a computer programmer when you grow up, programming is a useful and fun skill to have. Computers are very useful machines. The good news is that learning to program a computer is easy. If you can read this book, you can program a computer. A computer program is just a bunch of instructions run by a computer, just like a storybook is just a whole bunch of sentences read by the reader. These instructions are like the turn-by-turn instructions you might get for walking to a friend's house. (Turn left at the light, walk two blocks, keep walking until you find the first blue house on the right.) The computer follows each instruction that you give it in the order that you give it. Video games are themselves nothing but computer programs. (And very 1
fun computer programs!) In this book, any words you need to know will look like this. For example, the word "program" is defined in the previous paragraph. In order to tell a computer what you want it to do, you write a program in a language that the computer understands. The programming language this book teaches is named Python. There are many different programming languages including BASIC, Java, Python, Pascal, Haskell, and C++ (pronounced, "c plus plus"). When I was a kid most people learned to program in BASIC as their first language. But new programming languages have been invented since then, including Python. Python is even easier to learn than BASIC and it's a serious programming language used by professional computer programmers. Many adults use Python in their work (and when programming just for fun). The first few games we'll create together in this book will probably seem simple compared to the games you've played on the Xbox, Playstation, or Wii. They don't have fancy graphics or music but that's because they're meant to teach you the basics. They're purposely simple so that we can focus on learning to program. Games don't have to be complicated to be fun. Hangman, Tic Tac Toe, and making secret codes are simple to program but are also fun. We'll also learn how to make the computer solve some math problems in the Python shell. (Don't worry if you don't know a lot of mathematics. If you know how to add and multiply, you know enough math to do programming. Programming is more about problem solving in general than it is about solving math problems.) Downloading and Installing Python Before we can begin programming you'll need to install the Python software; specifically the Python interpreter. (You may need to ask an adult for help here.) The interpreter is a program that understands the instructions that you'll write in the Python language. Without the interpreter, your computer won't understand these instructions and your programs won't work. (We'll just refer to "the Python interpreter" as "Python" from now on.) Because we'll be writing our games in the Python language, we need to download Python first, from the official website of the Python programming language, http://www.python.org I'm going to give you instructions for installing Python on Microsoft Windows, not because that's my favorite operating system but because chances are that's the operating system that your computer is running. You might want the help of someone else to download and install the Python software. When you get to python.org, you should see a list of links on the left (About, News, Documentation, Download, and so on.) Click on the Download link to go to the download 2
The Featured Programs Most chapters begin with a sample run of the featured program. This sample run shows you what the program's output looks like, with what the user types in shown as bold print. This will give you an idea of what the complete game will look like when you have entered the code and run it. Some chapters also show the complete source code of the game, but remember: you don't have to enter every line of code right now. Instead, you can read the chapter first to understand what each line of code does and then try entering it later. You can also download the source code file from this book's website. Go to the URL http://inventwithpython.com/source and follow the instructions to download the source code file. Line Numbers and Spaces When entering the source code yourself, do not type the line numbers that appear at the beginning of each line. For example, if you see this in the book: 9. number = random.randint(1, 20) You do not need to type the "9." on the left side, or the space that immediately follows it. Just type it like this: number = random.randint(1, 20) Those numbers are only used so that this book can refer to specific lines in the code. They are not a part of the actual program. Aside from the line numbers, be sure to enter the code exactly as it appears. Notice that some of the lines don't begin at the leftmost edge of the page, but are indented by four or eight spaces. Be sure to put in the correct number of spaces at the start of each line. (Since each character in IDLE is the same width, you can count the number of spaces by counting the number of characters above or below the line you're looking at.) For example, you can see that the second line is indented by four spaces because the four characters ("whil") on the line above are over the indented space. The third line is indented by another four spaces (the four characters, "if n" are above the third line's indented space): 5 1 - Installing Python
while guesses < 10: if number == 42: print('Hello') Text Wrapping in This Book Some lines of code are too long to fit on one line on the page, and the text of the code will wrap around to the next line. When you type these lines into the file editor, enter the code all on one line without pressing Enter. You can tell when a new line starts by looking at the line numbers on the left side of the code. For example, the code below has only two lines of code, even though the first line wraps around: 1. print('This is the first line! xxxxxxxxxxxxxxx xxxxxxxxxxxx') 2. print('This is the second line! ') Tracing the Program Online You can visit http://inventwithpython.com/traces to see a trace through each of the programs in this book. Tracing a program means to step through the code one line at a time, in the same way that a computer would execute it. The traces web page has notes and helpful reminders at each step of the trace to explain what the program is doing, so it can help you better understand why these programs work the way they do. Checking Your Code Online Some of the games in this book are a little long. Although it is very helpful to learn Python by typing out the source code for these games, you may accidentally make typos that cause your game programs to crash. It may not be obvious where the typo is. You can copy and paste the text of your source code to the online diff tool on the book's website. The diff tool will show any differences between the source code in the book and the source code you've typed. This is an easy way of finding any typos in your program. Copying and pasting text is a very useful computer skill, especially for computer programming. There is a video tutorial on copying and pasting at this book's website at http://inventwithpython.com/videos/. The online diff tool is at this web page: http://inventwithpython.com/diff. A video 6
tutorial of how to use the diff tool is available from this book's website at http://inventwithpython.com/videos/. Summary This chapter has helped you get started with the Python software by showing you the python.org website where you can download it for free. After installing and starting the Python IDLE software, we will be ready to learn programming starting in the next chapter. This book's website at http://inventwithpython.com has more information on each of the chapters, including an online tracing website that can help you understand what exactly each line of the programs do. 7 1 - Installing Python
Topics Covered In This Chapter: Integers and Floating Point Numbers Expressions Values Operators Evaluating Expressions Storing Values in Variables 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. Let's start by learning how to use Python's interactive shell. Some Simple Math Stuff To open IDLE on Windows, click on Start > Programs > Python 3.1 > 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. 8
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 lizard. 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! Evaluating Expressions 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. However, if you just type 5 + into the interactive shell, you will get an error message. >>> 5 + SyntaxError: invalid syntax 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 Inside Other Expressions 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. 11 2 - The Interactive Shell
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. >>> spam = 15 >>> spam 15 >>> Now, spam evaluates to the value inside the variable, 15. And here's an interesting twist. If we now enter spam + 5 into the shell, we get the integer 20, like so. >>> spam = 15 >>> spam + 5 20 >>> 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: >>> spam = 15 >>> spam + 5 20 >>> spam = 3 >>> spam + 5 8 >>> The first time we enter spam + 5, the expression evaluates to 20, because we stored 13 2 - The Interactive Shell
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: >>> spam = 15 >>> spam + spam 30 >>> spam - spam 0 >>> 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. We can even use the value in the spam variable to assign spam a new value: >>> spam = 15 >>> spam = spam + 5 20 >>> 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: >>> spam = 15 >>> spam = spam + 5 >>> spam = spam + 5 >>> spam = spam + 5 >>> spam 30 14
>>> Overwriting Variables 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: >>> spam = 42 >>> print(spam) 42 >>> spam = 'Hello' >>> print(spam) Hello 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: >>> spam = 42 >>> print(spam) 42 >>> oldSpam = spam >>> spam = 'Hello' >>> print(spam) Hello >>> print(oldSpam) 42 In the above example, before overwriting the value in spam, we store that value in a variable named oldSpam. Using More Than One Variable When we program we won't always want to be limited to only one variable. Often we'll need to use multiple variables. 15 2 - The Interactive Shell
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 in order to use them later on. In the next chapter, we will go over some more basic concepts, and then you will be ready to program! 17 2 - The Interactive Shell
Topics Covered In This Chapter: Flow of execution Strings String concatenation Data types (such as strings or integers) Using IDLE to write source code. Saving and running programs in IDLE. The print() function. The input() function. Comments Capitalizing variables Case-sensitivity Overwriting variables 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. Strings 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 18
strings, we put them in between two single quotes ('), like this: >>> spam = 'hello' >>> The single quotes are there only to tell the computer where the string begins and ends (and is 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. >>> spam = 'hello' >>> spam 'hello' >>> Strings can have almost any character or sign in them as well as spaces and numbers. (Strings can't have single quotes inside of them without using an escape character. Escape characters are described later.) These are all examples of strings: 'hello' 'Hi there!' 'Albert' 'KITTENS' '7 apples, 14 oranges, 3 lemons' 'A long time ago in a galaxy far, far away...' 'O*&#wY%*&OCfsdYO*&gfC%YO*&%3yc8r2' As we did with numerical values in the previous chapter, we can also put string values in expressions. For example, the expression 4 * 2 + 3 is an expression with numerical values that will evaluate to the integer 11. String Concatenation 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: >>> 'Hello' + 'World!' 'HelloWorld!' >>> 19 3 - Strings
Hello world! What is your name? poop It is good to meet you, poop Variable Names 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. Casesensitive 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. Summary 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 26
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). 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. 27 3 - Strings
Topics Covered In This Chapter: import statements Modules Arguments while statements Conditions Blocks Booleans Comparison operators The difference between = and ==. if statements The break keyword. The str() and int() functions. The random.randint() function. The "Guess the Number" Game We are going to make a "Guess the Number" game. In this game, the computer will think of a random number from 1 to 20, and ask you to guess the number. You only get six guesses, but the computer will tell you if your guess is too high or too low. If you guess the number within six tries, you win. This is a good game for you to start with because it uses random numbers, loops, and input from the user in a fairly short program. As you write this game, you will learn how to convert values to different data types (and why you would need to do this). 28
Because this program is a game, we'll call the user the player, but the word "user" would be correct too. Sample Run of "Guess the Number" Here is what our game will look like to the player when the program is run. The text that the player types in is in bold. Hello! What is your name? Albert Well, Albert, I am thinking of a number between 1 and 20. Take a guess. 10 Your guess is too high. Take a guess. 2 Your guess is too low. Take a guess. 4 Good job, Albert! You guessed my number in 3 guesses! Enter this code exactly as it appears here, and then save it by clicking on the File menu and then Save As. Give it a file name like guess.py then run it by pressing the F5 key. Don't worry if you don't understand the code now, I'll explain it step by step. Guess the Number's Source Code Here is the source code for our Guess the Number game. When you enter this code into the file editor, be sure to pay attention to the spacing at the front of some of the lines. Some lines have four or eight spaces in front of them. After you have typed in the code, save the file as guess.py. You can run the program from the file editor by pressing F5. If you see an error message, check that you have typed the program in exactly as written. If you don't want to type all this code, you can download it from this book's website at the URL http://inventwithpython.com/chapter4. Important Note! Be sure to run this program with Python 3, and not Python 2. The programs in this book use Python 3, and you'll get errors if you try to run them with Python 2. You can click on Help and then About IDLE to find out what version of Python you have. 29 4 - Guess the Number