Chapter 2: Software Development in Python The goal of this textbook is to introduce you to the core concepts of computing through an introduction to programming in Python. In this chapter, we will focus our discussion on the software development process and help you set up your computer so that you can write your first Python programs. Section 1: The Software Development Process The formal study of how software is written and how it should be created is called Software Engineering. Although there is no universally agreed upon method on how software must be developed, we have over the years developed a number of best practices. Indeed, most large software companies have their own unique software development process as well as specific guidelines for how larger software should be written and even how the code itself should be formatted. In this section, we will present the various phases of software development and provide guidelines on how you should approach your programming assignments and projects. Section 1.1: Software and society The primary importance of well-constructed software is, of course, its value to society as a whole. Software has become an important part of our daily lives over the course of the last twenty years. The pervasiveness of software is only growing. When software goes wrong, its effects can range from irritating to life-threatening. The importance of correct software thus cannot be overstated. To give an example of how prevalent software is, consider that our refrigerators, and yes, even some toasters execute small embedded programs that control their functions. When such devices go wrong, it can be frustrating and inconvenient. When a device that uses a computer program produces an undesirable effect, or when a program itself produces an undesirable effect or crashes, we call this a software bug. Z s parents refrigerator had a buggy program that controlled the formation of ice cubes and defrosting of the freezer. The bug caused the system that controlled the defrost cycle to continually restart after the defrosting was completed. The net result was that the freezer was never cold enough to freeze any food and there was a continual stream of water leaking from the freezer from the defrost cycle. The technician was unable to fix the refrigerator since it was determined to be a software failure and the whole freezer needed to be replaced. Cars, airplanes, nuclear reactors, and other safety critical devices also utilize computer programs in their operations. Software for such devices must not fail as human lives are at stake when anything goes wrong. The software development process for such devices is strictly controlled and monitored. However, it is also very costly so much so that it would not be economical to use it in less critical situations like the refrigerator. However, there are a number of important things we can learn from such a stringent and monitored
development cycle. First and foremost, we see that well-planned and well-tested software typically exhibits fewer software bugs than inspired coding. Section 1.2: The stages of software development In this section, we will present seven stages of software development. Through the course of this textbook, we highly recommend that you utilize the first five when writing your own programs. Companies that sell their software mainly utilize the last two stages, as they revolve around consumers. Stage 1: Understanding the problem Although it may seem obvious, the first step in developing software is to fully understand what your software is to do. This means doing the appropriate due diligence and background research and reading. For instance, if we were writing a simulation of a particular phenomenon in physics, we should first research this phenomenon and understand the mathematical equations that govern the behavior of the phenomenon. If we do not have a good understanding of the mathematical underpinnings, we will not be able to write correct software that faithfully simulates the physics equations. For example, suppose we want to know how long a ball would fall from a given height before hitting the ground. Here, the first stage means that you need to understand the equation that govens free-fall and note that they assume neglecting air resistance. Then, the equation is given by the well-known formula s = (g t 2 )/2 Where s is the distance of the fall, g is the gravitational constant, and t is the time of the fall. We should also understand the units of these quantities and the value of the gravitational constant g. Stage 2: Design The next step in the software development process is to conceptually break down the program into a series of tasks that the software should be able to complete to achieve the goal of the program. This does not mean we need to think about how to write the program, but instead how to outline the tasks that need to be accomplished: how they flow from one task to the next, and how they interact. Effectively, you can view this step as drawing a flow chart for the program you will write. This will help you identify what algorithms you will need to come up with and in what order these algorithms should be executed. You can think of this stage as producing the blueprints for our program. In our free-fall example this means, first, that we solve the problem in three steps: (1) input the height s of the fall; (2) determine the time t of the fall; and (3) print t. Biut the design stage also includes re-arranging the formula for the fall so that we can solve for t, and choosing the units of the quantities. The formula becomes
t = sqrt( 2s / g ) Choosing meters for the height s and seconds for the time t, the gravitational constant becomes g = 9.81m/sec 2. Stage 3: Algorithms We now start to think about how to actually accomplish each task that we came up with during the design stage. In this step of the software development process, we construct algorithms for each task and sub-task. The algorithmic description of each task is not written in any programming language, but instead either in English or what we call pseudo-code. In this book, we will adopt English formulations to express our algorithms. This will allow us to separate the conceptual what from the how. This step focuses on what steps are necessary to arrive at the answer or goal of a given task or sub-task without worrying about concretely how we might write each of these steps in Python. This is a very important stage that is often overlooked by students learning to program. We find that students have a difficult time when they are both trying to figure out how to accomplish the goal of a given assignment and worrying about how to correctly write the Python code to accomplish the goal. By separating these two activities into separate activities, it reduces the burden of programming. For very large programs, this step is absolutely critical. In our example we would likely write the following conceptual program: 1. Request input of the height s 2. Compute 2*s/9.81, call it a 3. Compute sqrt(a), call it t 4. Print t Note that we decomposed the second step into two parts: computing the argument a of the square root, followed by computing the square root of a. Stage 4: Implementation During the preceding steps, we have not yet written any Python code, but now, in this stage, we can start worrying about how to go about implementing the algorithms we have developed. The algorithmic design as well as the conceptual flow chart for the program should act as a guide and implementation blueprint for the program. For each step in the algorithm we must write Python code that faithfully computes the result of that step. Once this has been completed for each step in each algorithm, the program has been written. We can then execute our program and see if it is correct. However, we highly recommend that you execute partial programs along the way. That is, whenever you write a few lines of code, you should check to see if those lines of code are doing what you expect them to be doing. It is much easier to find an error in a few lines of code than an error in hundreds of lines of code.
At this stage Python enters the picture for the first time. We have to learn to express the computations of Stage 3 in Python, and this will take some doing: In Chapter 3, we will learn how to request input of a number, how to print numbers, and how to compute simple formulae such as the one for a. Taking the square root, however, requires use of the math library which we will meet much later, in Chapter 7. Stage 5: Testing and debugging Once our program is written, we must validate that it correctly computes the result and faithfully implements the algorithms we wrote down in the previous stages of the software development process. This step in the software development process is often the longest. Debugging is a bit of a black art and takes practice, patience, and time to fully master. To help you learn how to debug your programs, each of the chapters will include one section suggesting how best to debug the constructs introduced in that chapter. We will present two mechanisms for debugging. The first method is to manually inject code into the program that will display what computations are being executed and what results are being produced. The second is to introduce a tool that aids in debugging and is a part of IDLE. This tool is called a debugger. For our example of the time of free fall this stage mostly addresses typing mistakes and mistakes in understanding how exactly some of the Python constructs work. This stage is of crucial importance: debugging programs is a skill that is absolutely necessary. Here, we have to face that we make mistakes, and nobody finds that thrilling. You will also get to know what are likely errors you make, and they may well be different from those your friend makes. If it helps, think of debugging as practicing playing a musical instrument. Stage 6: Deployment Once we have validated that our program is correct, we can release our program to the world. This often entails double-checking that the program works as intended on the particular computer the user will be running it on. In addition, this stage of the software development process includes the installation of the program and any necessary ancillary files that the program might use, such as large datasets for a scientific simulation. Stage 7: Maintenance and enhancement Once the program has been deployed, our job is, unfortunately, not over. Often times, as we all know, software bugs occur after deployment. In the maintenance phase of the software development process, the programmer will produce patches or fixes to the bugs that have been reported by the users of the program. In addition, some users may request additional functionality to be added to the program based on their individual needs. So not all patches to a program are aimed at fixing bugs; some introduce new functionality to a given program.
Section 2: Writing Code in Python Besides an open mind and a willingness to learn, you will need a programming environment. Programming environments are programs that allow you to type code and execute the code you wrote. The programming environment we will be using is called IDLE and is provided with the standard distribution of Python. Section 2.1: Downloading Python 3.1 Programming languages, just like English, evolve over time. To ensure the correct behavior of all the example programs and information presented in this book, it is important that you download the appropriate version of the language. Currently the most widely used versions of Python are Python 3.1.x and Python 2.7.x. We will be using Python 3.1.x exclusively. To find the correct version you simply need to use your favorite search engine and type in Python 3.1 Download. One of the first links should be: http://www.python.org/getit/releases/3.1/. Clicking on this hyperlink will take you to the main Python 3.1 webpage which will also allow you to download Python. You will notice a number of things on this webpage. The page will tell you what the major releases of Python are on the right hand side. It will also list the major changes in Python 3.1 over the previous version. Right now, most of these changes might seem meaningless, but once you have worked through this textbook, we encourage you to revisit this list to better understand the differences between the various versions of Python. If you scroll down toward the end of this webpage, you will find the download links.
The first two links provide all the source code for Python. Indeed, Python itself is a program! These two links are for advanced users that want to build custom versions of the installation or to make modifications to the language itself. The last three links are what we are interested in. The first is for 32-bit Windows operating systems and the second is for 64-bit Windows operating systems. If you are not sure which version of the operating system you have, you can click on the system properties box to find out. For example, on Windows 7, you would open the Control Panel, then System and Security, and then System. If you cannot find what operating system you are using, select the 32- bit download (Windows x86 MSI Installer(3.1)). All of the 64-bit Windows operating systems support executing 32-bit applications; they will just be a little less efficient. The version of Python 3.1 for the Mac is the last link. Section 2.2: Installing Python Installing Python is just the same as installing any other program. If you feel comfortable installing programs on your computer you can skip this section. The installation procedure should start automatically. However, if it does not, you will need to find the file you downloaded. At this point, we will tailor our instructions to the two flavors of operating systems you might be using. Please follow along for your type of operating system. Section 2.2.1: Mac If the installation did not start automatically, start by finding the file you just downloaded. For the Mac this will be the file: python-3.1.dmg. You can search for this file by opening up the Finder and typing the file name in the search field in the top right corner. The most probable location for this file is in the Downloads folder located in your main user account s folder. Once you locate the file, click on it to start the installation process. The computer will automatically decompress the files and open up a window that looks like the following:
If this window did not pop up, you can find it by opening Finder and clicking Python 3.1 under Devices. To continue with the installation click, on the open box icon called Python.mpkg. This should bring up the following installation window: You will need to click continue and then a new screen will appear in the installation window. This screen lists all the various pieces of software that come bundled with the Python installation, including the programming environment we will be using throughout this textbook. Click continue once again to bring up a new screen in the installation window. This screen provides the license agreement for the software. Read though the agreement and click continue. This will cause a small pop-up window to appear on the screen asking if you agree to the terms of the license agreement. Click yes to proceed to
the next step of installation, which will ask you what hard drive you would like to install Python on. Pick the hard drive on which you would like to install. When you select the hard drive, a green arrow will appear on its icon and you will be able to click the Continue button. This will bring up a new screen in the installation window. Click the Install button in the lower right corner. We suggest that you not change any of the settings on this screen. They will modify the exact location where the Python files will be located. Once you click install, the computer will install Python 3.1 and eventually you will see the following screen:
You have now successfully installed Python 3.1 on your computer and you are ready to proceed using it! Section 2.2.2: Windows If the installation did not start automatically, start by finding the file you just downloaded. For Windows, this will be one of two files: python-3.1.msi (for 32-bit systems) and python-3.1.amd64.msi (for 64-bit systems). You can search for this file by clicking the Window icon or Start icon in the lower left corner and typing this file name in the search field. The most probable location for this file is in the Downloads folder located in your main user account s folder. Once you locate the file, click on it to start the installation process. The computer will automatically decompress the files and open up a window that looks like the following:
This window asks whether or not you would like to give all user accounts on the computer access to Python. Pick whichever is appropriate for your computer. If you are not sure, select Install for all users and click Next. A new screen will appear in the installation window.
The default installation location for Python is in the C:\ root directory. If you would like to change the installation directory, select a new directory in the drop-down menu. Once you have picked the directory you would like Python to install into, click Next. A new screen will appear in the installation window.
On this screen, you can customize the installation of Python. We recommend the default installation, so no changes should be made on this screen. You simply need to click the Next button. This will install the needed files and programs on your computer. You have now successfully installed Python 3.1 on your computer and you are ready to proceed! Section 2.3: Python versions There are minor differences between minor releases of the language, but larger differences between major releases of the language. There are two major release of Python used today: Python 2.x and Python 3.x, of which minor releases Python 2.7 and Python 3.1 are most widely distributed. In this textbook, we will be using the latest major version of Python, but you may still encounter programs written using the earlier version of Python. Section 2.4: Python libraries Code libraries are collections of useful pieces of code that you can leverage in your own program to avoid re-inventing the wheel every time you want to perform a common task like picking the larger of two numbers or taking the square root of a number. You can also think of libraries as extensions to Python, which provide additional functionality. Programmers utilize libraries to quickly develop programs by re-using
software. The vast majority of libraries are provided free of charge. However, to utilize certain libraries you will need to pay for a license. The libraries discussed and presented in this book are all freely available and do not require you to purchase a license. In fact, we will see that Python provides a number of basic libraries that are included with the download. These libraries include functionality for using the internet, advanced mathematic operations, code that provides you with the ability to start other programs, and more. We will learn how to use libraries in our programs in Chapter 7. Section 3: IDLE The programming environment we will be using along with this textbook is called IDLE and has come packaged with the Python 3.1 installation. In this section, we will go through the basics of starting IDLE and the two ways to write and execute Python programs. We will also write our very first Python program! We will go into the details of this program in Chapter 3. Section 3.1: Starting IDLE In this textbook we will use IDLE as the main vehicle both for writing our Python programs and for executing them. It is important to note that there are other options for writing and executing Python programs. Once you are comfortable using IDLE and have worked through this textbook, we encourage you to try out other options. For the duration of the book, however, we expect you to use IDLE, as it is a great learning tool. Section 3.1.1: Starting IDLE on the Mac If you followed the instructions in the previous section, Python 3.1 will be installed in your applications folder. If you click on the Python 3.1 icon, it will expand to show the various programs that come bundled with Python 3.1. We will be using only IDLE in this textbook, but we encourage you to read through the documentation on the other tools as you may find them useful once you are comfortable writing Python programs. To start IDLE, you will need to click on the IDLE icon located in the Python 3.1 folder, which is located in the Applications folder. This will launch the IDLE programming environment and you will be able to start writing Python programs! There are two ways to write Python programs and we will examine both in the following sections.
Section 3.1.2: Starting IDLE on Windows If you followed the instructions in the previous Section, Python 3.1 will be installed in your C:\ root directory. To launch the IDLE program, click on the windows icon and then select All Programs. When you click on the Python 3.1 folder, you will see an icon for IDLE. Double click on the IDLE icon to launch the IDLE programming environment. This will launch the IDLE programming environment and you will be able to start writing Python programs! There are two ways to write Python programs and we will examine both in the following sections. Section 3.2: Interactive mode (Python Shell) One of the main benefits of Python is that it provides an interactive mode for programming. An interactive mode for programming allows you to both type and execute code at the same time. The way it works is that you type one line of code and Python executes it. This means you are effectively adding that line of code to whatever lines of code you have already typed into the interactive mode. For our purposes, this means that if you are ever curious about what a particular piece of code will do or what effects it will produce, you simply need to type that code into the interactive mode and find out! We strongly encourage you to play around and test out various pieces of code in the interactive mode. The interactive mode is the default mode for IDLE. In Python, we call this interactive mode the Python Shell. When you start IDLE, it automatically brings up the Python Shell. You will notice a line that starts with three greater-than signs (>>>). This is called the prompt, and it is where you will type in your Python code. When you hit enter, Python will attempt to execute the code you have written. If the code is correct Python, the result of executing this line of code will be displayed on the following line.
Let s write our first Python program! At the prompt, type the following line: print( Hello World! ) and then hit the enter key. Python will execute this program and should display Hello World! on the next line of the shell before providing you with another prompt. Congratulations! You have just written your first Python program! We will present many examples throughout this textbook. The vast majority of them will be written using the Python shell. When we present example programs we will use the following structure: >>> print("hello World!") Hello World! The above structure is how we will present programs from now on. It represents our first Python program, which we executed in the Python Shell. Notice that we include the >>> for the prompt to differentiate between the lines of code that we typed and the lines that the program outputted. The indented paragraphs that follow a program will contain an explanation of the program and what is going on under the hood. Section 3.3: Running a Python script For larger programs, or programs that we want to run multiple times, using the shell is not efficient. One problem with the interactive mode is that you cannot save your work to use at a later time. For longer programming sessions and programs that you would like to keep we create Python scripts. Python scripts are the term that computer scientists use to refer to Python programs. For the duration of this textbook, we will use script and program synonymously, as the differences are not important for our work. To start writing a program that you can save in a file you need to open IDLE like we have done before. You will see the Python shell pop up. Click on the File menu and select New Window. This will open up a new blank window into which we can type Python code. You will notice that when you hit the enter key, the program is not run; instead, the
cursor simply moves to the next line. This means you can type as many lines of Python code as you would like prior to executing the program. Type the following program in the window that was created when you selected New Window. Notice that in this program, we typed the contents of our previous program twice. What do you think will happen if we execute this program? Since we are not using the Python shell we need to explicitly tell Python we want our program to be executed. However, before we execute our program, let s go ahead and save it. To do this, click on the File menu and select Save. This will prompt you to name your program and choose a location for the file. We recommend the Documents folder on the Mac and the My Documents folder on Windows. Once you have saved your program, click on Run menu (note that the Run menu only appears when you have selected the window into which you typed your Python program). From the Run menu select Run Module. The output from running your program will be displayed in the Python shell window. You should see the following output after you clicked on Run Module. Is this output what you expected? We will learn why it should be in Chapter 3. If you would like to run this program again, you simply need to click the Run menu and select Run Module one more time. Try modifying the program so that Hello World! is displayed three times when you run the program. You can make modifications to your program by clicking on the window in which your program is displayed and typing in the changes. You will need to save your modified program prior to running it.
To open a program you have previously written, first open IDLE. Then, from the File menu, click Open. The next step is to find where you saved your file. If you followed our advice, it will be in the Documents or My Documents folder. When you select your file, it should open up a new window that displays the Python code. Section 4: Chapter Summary In this chapter we introduced the importance of correct software and provided a brief explanation of the stages of the software development process. The first five stages apply to this textbook and the last two stages are for commercial software. You will be welladvised to follow this process, even when deadlines loom. Chances are the debugging phase, stage 5, will go much faster and be much less frustrating. We provided an extensive tutorial on how to download, install, and run our first programs in Python 3.1. It is absolutely crucial to get the installation right as it is a prerequisite to be successful in this course. If you have difficulty, seek help from the instructor and the course staff. Section 5: Exercises and Review Questions Did the installation go well? Were there unclear passages and if so, which ones?