Learning to Program Using Python
Total Page:16
File Type:pdf, Size:1020Kb
Learning to Program Using Python Cody Jackson 2 Copyright © 2009-2013 Cody Jackson. This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. The source code within this text is licensed under the GNU General Public License (GPL). The following license information covers all code contained herein, except those that explicitly state otherwise: Copyright © 2006-2011 Cody Jackson. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. Contents ITheCoreLanguage 1 1 Introduction 3 1.1 Why Python? . 4 1.2 Why Another Tutorial? . 5 1.3 Getting Python . 6 1.4 Conventions Used in this Book . 7 2 How is Python Different? 9 2.1 PythonConcepts ...................... 9 2.1.1 Dynamic vs. Static Types . 9 2.1.2 Interpreted vs. Compiled . 10 2.1.3 Prototyping . 11 2.1.4 Procedural vs. Object-Oriented Programming . 12 3 Comparing Programming Languages 13 3.1 C . 14 3.2 C++............................. 15 3.3 Java . 16 3.4 C#.............................. 18 3.5 Python . 22 4 The Python Interpreter 25 4.1 Launching the Python interpreter . 25 4.1.1 Windows . 26 4.1.2 Mac . 26 4.2 Python Versions . 27 i ii CONTENTS 4.3 UsingthePythonCommandPrompt . 28 4.4 CommentingPython . 29 4.5 Launching Python programs . 29 4.6 Integrated Development Environments . 30 5 Types and Operators 33 5.1 Python Syntax . 33 5.1.1 Indentation ..................... 33 5.1.2 Multiple Line Spanning . 35 5.2 Python Object Types . 35 5.3 Python Numbers . 37 6Strings 39 6.1 Basic string operations . 40 6.2 Indexingandslicingstrings . 42 6.3 String Formatting . 43 6.4 Combining and Separating Strings . 45 6.5 Regular Expressions . 47 7Lists 49 7.1 List usage . 50 7.2 Adding List Elements . 51 7.3 Mutability . 54 7.4 Methods . 54 8 Dictionaries 57 8.1 Making a dictionary . 58 8.2 Basic operations . 59 8.3 Dictionary details . 61 8.4 Operation . 61 9 Tuples 63 9.1 Why Use Tuples? . 64 9.2 Sequence Unpacking . 65 9.3 Methods . 66 CONTENTS iii 10 Files 69 10.1 File Operations . 70 10.2 Files and Streams . 70 10.3CreatingaFile ....................... 71 10.4 Reading From a File . 72 10.5 Iterating Through Files . 75 10.6 Seeking . 76 10.7 Serialization . 77 11 Statements 79 11.1 Assignment . 80 11.2 Expressions/Calls. 82 11.3 Printing . 82 11.4 if Tests........................... 83 11.5 while Loops . 85 11.6 for Loops . 86 11.7 pass Statement . 88 11.8 break and continue Statements . 89 11.9 try, except, finally and raise Statements . 89 11.10import and from Statements . 89 11.11def and return Statements . 89 11.12ClassStatements . 90 12 Documenting Your Code 91 13 Making a Program 99 13.1 Making Python Do Something . 100 13.2 Scope . 103 13.3 Default Arguments . 104 14 Exceptions 107 14.1 Exception Class Hierarchy . 110 14.2 User-Defined Exceptions . 112 15 Object Oriented Programming 115 15.1 LearningPythonClasses. .115 15.2 HowAreClassesBetter?. .116 15.3 Improving Your Class Standing . 116 iv CONTENTS 15.4 So What Does a Class Look Like? . 118 15.5 “New-style”classes . .120 15.6 A Note About Style . 121 16 More OOP 123 16.1 Inheritance .........................123 16.2 Operator Overloads . 125 16.3 ClassMethods .......................127 16.4 Have you seen my class? . 128 17 Databases 131 17.1 How to Use a Database . 132 17.2 Working With a Database . 132 17.3 Using SQL to Query a Database . 133 17.4 Python and SQLite . 135 17.5 Creating an SQLite DB . 135 17.6 Pulling Data from a DB . 137 17.7 SQLite Database Files . 140 18 Distributing Your Program 143 19 Python 3 145 II Graphical User Interfaces (GUIs) 147 20 Graphical User Interfaces 149 20.1 Introduction. .149 20.2 Popular GUI Frameworks . 150 20.3 Before You Start . 152 21 A Simple Graphical Dice Roller 155 22 What Can wxPython Do? 163 III Web Programming & Game Development 167 23 Developing for the Web 169 CONTENTS v 23.1 ChooseYourPoison . .169 23.2 Karrigell Web Framework . 170 23.2.1 Python Scripts . 172 23.2.2 Karrigell Services . 172 23.2.3 PythonInsideHTML . .173 23.2.4 HTMLInsidePython . .173 23.2.5 HTMLTags . 174 23.2.6 Template engine integration . 175 23.2.7 Karrigell Templates . 175 23.3 What’sIncluded?. .177 24 Game Development 179 24.1 PyGame . 179 24.1.1 Game Development with PyGame . 180 24.1.2 PyGame Limitations . 180 24.2 Parts of a Video Game . 181 24.2.1 Game Engine . 181 24.2.2 Input ........................181 24.2.3 Graphics . 181 24.2.4 Audio . 182 24.2.5 UserInterface. .182 24.3 A Sample Game . 182 24.4 PyGame Modules . 184 A String Methods 189 B List Methods 195 C Dictionary operations 197 D Operators 201 ESampleprograms 203 E.1 Dice rolling simulator . 203 E.2 Temperature conversion . 207 E.3 Game character attribute generator . 208 E.4 Text-based character creation . 211 F GNU General Public License 233 vi CONTENTS Part I The Core Language 1 Chapter 1 Introduction IoriginallywantedtolearnPythonbecauseIwantedtomakeacom- puter game. I had taken several programming classes in college (C, C++, and Java) but nothing really serious. I’m not a Computer Sci- ence major and I don’t program on a professional level. I didn’t really like the low-level work involved with C/C++. Things like pointers, memory management, and other concepts were difficult for me to grasp, much less effectively use. Java, as my first pro- gramming class in school, didn’t make any sense. I had never used an object-oriented language before and object-oriented programming (OOP) concepts gave me fits. It probably didn’t help that my Java class wasn’t actually real Java; it was actually Microsoft’s “custom” version: J++. So not only was I learning a language that had little practical use (J++ added and cut many features found in real Java), but the programs didn’t work correctly. Ultimately the class was can- celed near the end of the semester and everyone received full credit. These problems, and issues learning other programming languages, left a bad taste in my mouth for programming. I never thought I learned a language well enough to feel comfortable using it, much less actually enjoy programming. But then I heard about Python on a computer forum, and noticed several other mentions of the language at other sites around the Internet. People were talking about how great the language was for personal projects and how versatile it is. I decided to give programming one more try and see if Python was the 3 4 CHAPTER 1. INTRODUCTION language for me. To give me more incentive to learn the language, I decided to recre- ate a role playing game from my childhood as a computer game. Not only would I have a reason to learn the language but, hopefully, I would have something useful that I could give to others for their enjoyment. 1.1 Why Python? Python is regarded as being a great hobbyist language, yet it is also an extremely powerful language. It has bindings for C/C++ and Java so it can be used to tie large projects together or for rapid prototyping. It has a built-in GUI (graphical user interface) library via Tkinter, which lets the programmer make simple graphical interfaces with little effort. However, other, more powerful and complete GUI builders are available, such as Qt and GTK+. IronPython, a Python version for Windows using the .NET framework, is also available for those using Microsoft’s Visual Studio products. Python can also be used in a real- time interpreter for testing code snippets before adding them into a normal “executable". Python is classified as a scripting language. Generally speaking, this just means that it’s not compiled to create the machine-readable code and that the code is “tied-into” another program as a control routine. Compiled languages, such as C++, require the programmer to run the source code through a compiler before the software is can be used by a computer. Depending on the program’s size, the compilation process can take minutes to hours. Using Python as a control routine means Python can act as a “glue” between different programs. For example, Python is often used as the scripting language for video games; while the heavy-duty work is performed by pre-compiled modules, Python can act in a call/re- sponse fashion, such as taking controller input and passing it to the appropriate module. Python is also considered a high-level language, meaning it takes care of a lot of the grunt work involved in programming. For example, Python has a built-in garbage collector so you, as a programmer, don’t really need to worry about memory management and memory leaks, a common occurrence when using older languages such as C.