Python for CTI-110 James A. Carrier, Ph.D. July 26, 2014 2 Contents 1 A Brief History 1.1 History of Computers and Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2 Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3 Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 What Is so Great about Python? 2.1 Cross-Platform . . . . . . . . . . . 2.2 Python is Free . . . . . . . . . . . 2.3 Highly Interactive . . . . . . . . . 2.4 Python Scaffold . . . . . . . . . . . 2.5 Intuitive Syntax . . . . . . . . . . . 2.6 Installing Python . . . . . . . . . . 2.7 Working in the Python IDLE Shell 2.8 Exercises . . . . . . . . . . . . . . 2.9 Getting Help from Python . . . . . 2.10 Saving Code in Python Files . . . 2.11 Using the Print Function . . . . . 2.12 Using the Comment Statement . . 2.13 Two Types of Variables . . . . . . 2.14 Exercises . . . . . . . . . . . . . . 5 5 7 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 9 9 9 9 9 10 11 12 12 13 14 16 16 17 3 Designing Programs with Functions 3.1 Obtaining Input from the Keyboard . . . 3.2 Simple Functions . . . . . . . . . . . . . . 3.3 Functions which Return a Value . . . . . 3.4 Input, Processing, and Output Functions 3.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 19 21 22 23 25 4 Structures that Make Decisions 4.1 The IF Statement . . . . . . . . 4.2 Relational and Logical Operators 4.3 Boolean Variables . . . . . . . . . 4.4 An ATM Machine . . . . . . . . 4.5 The ELIF Structure . . . . . . . 4.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 27 27 28 28 29 30 5 Answers to Selected Exercises 5.1 Answers to Exercises 2.8 . . . 5.2 Answers to Exercises 2.14 . . 5.3 Answers to Exercises 3.5 . . . 5.4 Answers to Exercises 4.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 31 31 32 33 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 4 CONTENTS Introduction Python is a scripting language with many faces such as Python (2.7), Python (3.4), bPython, brPython, cPython, vPython, and PyGame, just to name a few. In additon, Python is cross-platform, meaning that it runs equally well on Windows, Mac and Linux. This book is written with the assumption that the reader is a beginner with respect to Python, but does assume the reader has a basic knowledge of windows and computers in general. Good luck and happy programming! Chapter 1 A Brief History 1.1 History of Computers and Programming Figure 1.1: A Computer Circa 1975 Depending on one’s definition of what a computer is, one could argue that computers began as early as 1939, or perhaps even earlier. For our purposes in this text, we will begin looking at computers in the early 1950s. Circa 1950, some of the first computers were designed by agencies such as The National Bureau of Standards. Acronyms were the common names of these computers. For instance, SEAC is an acronym for Standards Eastern Automatic Computer. Located in Washington, it became a laboratory for testing components and systems for setting computer standards. The SEAC was the first computer to use all-diode logic, a technology more reliable than vacuum tubes, and the first stored-program computer completed in the United States. In the 1960s computers were still very large and produced large amounts of heat. They also cost a great deal of money. One computer could cost as much as $120,000.00. The computers in the 1960s were the precursor to the minicomputer. The minicomputer was smaller than those of the 1950s. In the 1950s computers took up an entire room. The minicomputer was considerably smaller, yet could do as much or more than the room-sized computers. Steve Jobs of Apple worked in the early 1970s with Xerox which developed the personal computer graphical user interface, an object oriented programming language known today by its acronym OOP. At this time computer programs were stored on tape, drums and the floppy disk. In the 1980s, Seagate Technology created one of the first hard disk drives for microcomputers. Also, during this time, many computer programming languages were being developed. Table 1.1 lists some some of the more popular languages of the era. 5 6 CHAPTER 1. A BRIEF HISTORY Table 1.1: Programming Languages Language Ada BASIC FORTRAN COBOL Pascal C Description The U.S. Department of Defense used Ada in the 1970s. There are many influential people in the field of programming and sometimes languages are named after them. The language Ada was named after a woman known as Countess Ada Lovelace. BASIC is the acronym for Beginners All purpose Symbolic Instruction Code. It was developed in the 1960s and was designed to be so simple that even beginners could learn to program. FORTRAN too is an acronym for FORmula TRANslator. Although it was developed in the 1950s it was still widely used into the 1970s. The acronym for COBOL is Common-Business Oriented Language. It was designed in the 1950s and is still being used today. Pascal, created in the 1970s, was originally a language for teaching programmers how to program. It was named after the mathematician Blaise Pascal who is famous for conceiving of the idea of Pascal’s triangle. C was created in the 1970s by Bell Laboratories. It is a very powerful language and the more modern versions are known as C++ and C#. In the 1990s, we saw the introductions of MS-DOS and Microsoft Windows operating systems, both developed by Bill Gates and Microsoft, Inc. Of course Windows 7 and 8 are descendants of the early versions of Windows. Another very important development occurred in the 1990s when Tim Berners-Lee conceived of the Internet while he was a researcher at CERN. Berners-Lee developed HyperText Markup Language known today as HTML. Table 1.2 lists some of the languages developed after the 1980s. Table 1.2: More Recent Programming Languages Language C# Java JavaScript PHP Visual Basic Python Description Circa 2000, Microsoft created C# to interface with the Microsoft.NET framework platform. Java, created by Sun Microsystems, runs on a Java Virtual Machine platform making it cross-platform. Java code can be run from the client or the server machine, giving it much versatility. JavaScript is not similar to Java. JavaScript does not create applets or stand-alone applications. In its most common form, JavaScript resides inside HTML documents, and can provide levels of interactivity to web pages that are not achievable with simple HTML. PHP is a widely used scripting language which resides on the server-side as well as on the client machine. PHP, like JavaScript, can be mixed with HTML code. Visual Basic is widely used in Microsoft Office to create and write macros and goes by the name Visual Basic for Applications or VBA. Visual Basic itself is commonly called VB. VB is typically taught inside the Microsoft Visual Studio, thus giving beginning programmers an introduction to Visual Studio. Python is the language we use in this text. Python scripts can be stored inside .py files or .txt files. Typically, Python scripts are not compiled into executable code until the project is complete. Python can reside on the server-side or the client-side thus giving Python full access to the Common Gateway Interface or CGI. Python has grown in use and popularity since 2000 and is used throughout the Internet, for example, both Google and youTube utilize Python extensively. The current version of Python can be found at https://www.python.org. 7 1.2. HARDWARE 1.2 Hardware The physical aspects of a computer are the items you can touch and comprise the hardware of a computer. Thus, items such as Central Processing Unit (CPU), Main Memory (RAM), output devices such as monitors and printers are considered hardware. Table 1.3 lists some common output and input devices. Table 1.3: Common Devices Output Monitor Printer Speakers Hard Drive Input Mouse Keyboard Drawing Tablet Hard Drive It is common for computer experts to choose between hardware and software. It has been said that one cannot be a expert in hardware without knowing quite a bit about software. It is also true that one cannot become an expert in software without knowing a great deal about hardware. Thus, we find it is common to divide computer workload assignments between hardware specialists and software specialists. 1.3 Software The programs which run on your computer hardware are referred to as software. Software can be divided into several categories such as operating system software and application software. Below is a table which helps in the understanding of this division. Table 1.4: Software Classifications Operating System Software Windows 8 Windows 7 Linux Unix Application Software Microsoft Word Microsoft Excel Microsoft PowerPoint Adobe Reader Typically, software resides on the computer’s hard drive. When the programmer opens the software package, the contents of the package are loaded into the RAM of the computer. Now the software can be modified by the programmer without actually having to physically touch the software. Once all the changes are made, the software is then saved back to the hard drive. Since many of these actions are abstract in nature, some consider becoming a software expert a bit challenging. This of course is not true for everyone. 8 CHAPTER 1. A BRIEF HISTORY Chapter 2 What Is so Great about Python? 2.1 Cross-Platform Programs, when written in languages such as C++ and Visual Basic inside Visual Studio, do not run without modification under Linux. However, a program written in Python can be run in Linux without any code modifications. In other words, the Python code can be transferred directly to the Mac and it runs seamlessly. There are a few exceptions to this rule, especially if the Python program in question is extremely complex. Perhaps then, some code lines may need to be modified slightly, but not nearly as many lines of code as would be necessary under other languages. When a language can run on multiple operating system platforms without modifications, it is called cross-platform. 2.2 Python is Free Python is free and is available for download for anyone wishing to become proficient in Python programming. There is a worldwide Python user community, available 24/7 to help users work through issues. It is a general purpose language meaning that it is designed to handle contemporary applications including networking applications and media applications. Python can be downloaded from https://www.python.org. 2.3 Highly Interactive In Python it is very simple to get input from the user while building complex code. From the input the programmer can then use program statements to evaluate the user input. Since the Python code is very simple, the programmer can then merge and compile tested and verified code into larger saved programs known as modules or even stand-alone applications. 2.4 Python Scaffold In Python it is very easy for beginners to write simple programs and then branch out and write more complex programs once they “get their feet wet”. Yet Python does not forget the advanced users because it provides methods for object oriented project development. This means that Python can be used to develop full blown Windows applications. 2.5 Intuitive Syntax Python provides syntax that is very close to the syntax of English, for example, print(“The cat in the hat”). Therefore, it is comparatively easy to convert pseudo code into Python code with little changes needed when compared to that of other programming languages. Any programming statement which violates the syntax rules of the Python interpreter will generate a syntax error. The mathematical syntax of Python is very 9 10 CHAPTER 2. WHAT IS SO GREAT ABOUT PYTHON? close to that of conventional algebra, thus reducing the time needed in learning to build working formulas in Python. 2.6 Installing Python To install the latest version of Python, the student should look to the online student resource if their institution has one such as Blackboard or Moodle, and find the provided *.msi file for download and installation. Your instructor will give you more information about locating the *.msi file if this is the manner he/she wishes to utilize. On the other hand, if you are expected to download and install Python on your own, then below are the instructions to do so. The steps to download and install Python on Windows: Figure 2.1: A Typical Python Download Page 1. Navigate to https://www.python.org. Once there look for a download page. Since the website changes often, it may or may not look exactly like Figure 2.1. 2. I chose “Windows x86-64 MSI installer” but you should choose what is correct for the system on which you are installing Python. 3. Once the file has downloaded and been saved to your hard drive then double click on the file to launch the installation process. The first screen in the installation process is pictured in Figure 2.2 below. Click ‘next’ on that screen and continue to take all the default settings until the installation is complete. 11 2.7. WORKING IN THE PYTHON IDLE SHELL Figure 2.3: The IDLE/Python Icon Figure 2.2: A Python Installation Screen 4. After the installation of Python is complete, look for the IDLE/Python icon, pictured in Figure 2.3, on your desktop screen and double click it to open up Idle. The Idle window looks like the figure pictured in Figure 2.4. In the section following we will learn how to place program code fragments into the Python shell. 2.7 Working in the Python IDLE Shell In the last section we learned how to open the IDLE shell in Windows. On the Mac, users should launch a terminal window and type the command idle3. Once the IDLE window has appeared as illustrated in Figure 2.4 the user can enter program code fragments and obtain responses to aid in learning how to program in Python. IDLE stands for “Integrated DeveLopment Environment”. It is an element of programming that beginners must learn about almost all programming packages. Figure 2.4: The IDLE Window To run a code fragment in the IDLE shell, you type after the >>>symbol and press the Return key. The shell will respond with an answer, a display of text, or that it encountered a syntax error as caused in our example by asking for something which Python shell does not understand. See Figure 2.5. The red font indicates that IDLE has encountered an error. Look for the word “Traceback” and read down from there. The reader should take some time here and practice by typing the following exercises into the shell to see if the output returned by your computer is the same as the output found in Figure 2.5. 12 CHAPTER 2. WHAT IS SO GREAT ABOUT PYTHON? Figure 2.5: The IDLE Shell after Entering Code Fragments Let us >>> >>> >>> >>> >>> begin by typing the following program fragments: 2 + 2 and press Return 5+4+3 and press Return 7/2 and press Return “Hello World” and press Return sqrt(15) and press Return When working in the shell the following table of operations is helpful: Table 2.1: Math Operators in Python Symbol + * / ** 2.8 Operation Addition Subtraction Multiplication Division Exponentiation Description Adds two numbers Subtracts the second number from the first Multiplies one number by another number Divides the first number by the second number Raises the first number to the power of the second number Exercises 1. Using the Python shell find the sum of the first 10 numbers. You would enter 1+2+3+4+5+6+7+8+9 +10 beside the >>>prompt. 2. Using the Python shell find the quotient of 365/7. You would enter 365/7 beside the>>>prompt. 3. Using the Python shell find the answer to this expression: 1 + 2 * 3. 4. Using the Python shell find the answer to this expression: (1 + 2) * 3. 2.9 Getting Help from Python One way to get help is to locate the Python documentation. This can be done by using the help menu in the Python shell or pressing F1 while in the Python shell, which will take you to a screen similar to that pictured in Figure 2.7. Another way to get help is to use the help() function in the Python shell. For example, type help(abs) to obtain help concerning the abs() in Python as illustrated in the Figure 2.8. 13 2.10. SAVING CODE IN PYTHON FILES Figure 2.6: Getting to the Documentation Figure 2.7: The Python Documentation Figure 2.8: Using the Help() Function 2.10 Saving Code in Python Files So far, we have only typed our program code snippets into the Python shell. The problem with typing code snippets into the Python Shell is that the next day when you wish to work in the shell again you must type in your code a second time. In this lesson you will learn how to save your work and edit a program using an additional window called the Python editor. The Python editor allows users to enter programming statements, test and run the statements, and then save the statements into a file that will have a file extension of .py. In the following exercise we will write a simple program which prints “Hello World” to the IDLE screen. We will then save and close the program and re-run the program after opening the saved file. Below are the steps to writing, saving and running a program. In Figure 2.9 we see how it should look when the program is done. 1. Open IDLE 2. From the File menu choose new. A new window appears with the phrase “Untitled” in the title bar. 3. Type in the command print(“Hello World”). Be very careful how you type the print command because it MUST be typed exactly as shown. If you make a mistake or a change you will get a syntax error. 4. Click the “run” menu in the window on the right and from the menu which appears choose “Run Module F5”. When you do, Python reminds you that you have not saved your program yet so click the OK button to advance to the SaveAs dialog box. 14 CHAPTER 2. WHAT IS SO GREAT ABOUT PYTHON? Figure 2.9: The Window on the Right Contains a Python Program 5. Type in the name “MyFirst” and click the save button. The program then runs and outputs “Hello World” to the IDLE screen and then ends. Notice the title bar for the window on the right. Notice that the name of the file has changed from Untitled to MyFirst.py. Several things happened when your program was saved. First, a .py file extension was appended to the name you gave your program. Second, your program was stored into the Python34 directory of your drive C: unless you installed Python some place else. 6. Now close the Python shell and the editor window. Now we wish to run the saved program entitled “MyFirst”. There are many ways to accomplish this, and the one discussed here is a commonly used method. 7. Open IDLE 8. From the File menu choose new. A new window appears with the phrase “Untitled” in the title bar. 9. From the file menu in the editor windows choose Recent Files and then click on “MyFirst”. 10. Click the “run” menu from the editor window and from the menu which appears choose “Run Module F5”. 11. The program called “MyFirst” should run without error. Now compare your IDLE window against Figure 2.9. 2.11 Using the Print Function The print function is used to display information in Python, whether working in the shell or inside a program. In the program in Figure 2.9 we used the print statement to print the message “Hello World”. The syntax or the rules for using the print statement successfully are described below. First type the word “print” followed by an open parenthesis. Remember you cannot capitalize the p. Next you may use either the single quote ‘ or the double quote “. Enter the message you wish displayed. Close your quote and close your parenthesis. Remember to be consistent. For example, you cannot begin your message string with a double quote and end with a single quote. That would cause a syntax error as shown in Figure 2.10. Notice the title of the pop-up box is SyntaxError. Additional information is given, i.e. “EOL while scanning string literal”. EOL is an acronym for “End of Line”. Dealing with Program Errors Another type of syntax error which can occur due to misspelling or capitalizing the p in print is shown in Figure 2.11. The red font indicates that IDLE has encountered an error. Look for the word “Traceback” and read down from there. The print function can print many things other than messages or strings. It can also print the contents of variables. 15 2.11. USING THE PRINT FUNCTION Figure 2.10: A Syntax Error Figure 2.11: A More Common Syntax Error Figure 2.12: Printing Variables Figure 2.13: Radius Does Not = radius Variables are words or letters that have been assigned a value or perhaps a message. For example, consider the following program statements: PI=3.14159 Radius=21 print(PI, Radius) Notice we are not using quotes inside the parentheses of the print function since we are printing the contents of variables. In the left window in Figure 2.12, notice that the program ran just fine and printed the values of PI and Radius. However, in the left window in Figure 2.13 we see a syntax error because the second time I did not capitalize the R in radius, thus Python did not find the value for Radius when it tried to print Radius. Python reports the error: name ‘radius’ is not defined. Table 2.2 has a few rules Python requires about naming variables. 16 CHAPTER 2. WHAT IS SO GREAT ABOUT PYTHON? Table 2.2: Python Variable Naming Rules 1. 2. 3. 4. 5. 2.12 Uppercase and lowercase characters are distinct, therefore, Radius is not the same as radius. A variable cannot contain spaces. You may use A through Z, a through z or an underscore as the first digit, but you may not begin a variable with a digit such as 0 through 9. After the first character you may use the digits 0 through 9, A through Z, a through z or an underscore. Python has keywords such as print or input and therefore you cannot use keywords as variable names. Using the Comment Statement Comments are used in programs to help humans understand the coding inside programs. Comment statements are used in virtually all programming languages and almost all languages identify a comment statement differently. In Python, a statement which begins with the # sign is a comment statement. So we could help the reader understand our program called “MyFirst” by inserting a comment statement at the beginning of our code. Figure 2.14 pictures “MyFirst” with a comment inserted. Programs completely ignore comment statements and their existence makes no difference in the output. Figure 2.14: MyFirst with a Comment Statement 2.13 Two Types of Variables There are actually many types of variables, but by far the most common variables are “string literals” and numbers. X=25 The variable X is an example of a numerical variable. Things get a little more complicated when we realize that numerical variables can be of two different types, integer (abbreviated int) and float. Basically, when a number has a decimal in it, it is considered a float in Python. For example, Y=6.142857 In this case Y is considered a float, whereas X is considered an int. Z=“The cat in the hat.” The variable Z is considered a “string literal”. 2.14. EXERCISES 2.14 17 Exercises 1. Write and save a program which finds the area of a circle. Let X represent a radius of 7 and PI represent 3.14159. Store the answer in the variable Area and print(Area). 2. Modify the program you wrote for Exercise 1 and store in variable Z the value “The area is =”. Also, modify your print function to say print(Z,Area). 3. Write a program to find the area of a rectangle with length = 7 and width = 3. Remember the area of a rectangle is simply the length times the width. 4. Write a program to find the area of a triangle with base = 7 and height = 9. Remember the area of a triangle is found by taking 1/2 the base times the height. 18 CHAPTER 2. WHAT IS SO GREAT ABOUT PYTHON? Chapter 3 Designing Programs with Functions 3.1 Obtaining Input from the Keyboard The programs we wrote previously lacked a method to change the value of the variables. For example, it would be nice to ask the user to key in the length of the radius and when he/she pressed Enter, the program would display the area of the circle. Currently we would need to modify the program each time we wished to calculate the area of a circle with a different radius. In Python the most common method of obtaining information from the user is with the input statement. The syntax of the input statement is as follows: radius=input(“prompt”) When the user runs the program, the user will see the word “prompt” on the screen. Let us suppose the user types in 21. Then 21 will be stored in the variable radius. Then the program could proceed to calculate the Area and display the answer. Below is the code to execute such a program. The input statement has been modified to ask the user to “Please enter the radius: ”. Program listing Example 3.1 does not run as expected but gives an error. The error is displayed in Figure 3.1. Example 3.1 # Example 3.1 PI =3.14159 radius = input ( " Please enter the radius : " ) Area = PI * radius **2 print ( " The area is = " , Area ) Figure 3.1: An Unexpected Error 19 20 CHAPTER 3. DESIGNING PROGRAMS WITH FUNCTIONS The error is because the input statement expects a “string literal” from the user but the int 21 was typed. The solution is to convert the input statement into an int by nesting it inside the int() function as shown below. The corrected program is given in Figure 3.2. The corrected line of code is: radius=int(input(“Please enter the radius: ”)) Example 3.2 # Example 3.2 PI =3.14159 radius = int ( input ( " Please enter the radius : " )) Area = PI * radius **2 print ( " The area is = " , Area ) Figure 3.2: The Input Function is Correctly Nested Inside the Int Function The program now works as planned! It is rare that programmers get it right the first time, especially with more complex programs than these. Such development of programs is called “The Program Development Life Cycle”. It is composed of a series of steps which are cyclical in nature. A typical “Program Development Life Cycle” is given in Figure 3.3. Figure 3.3: The Program Development Life Cycle Programs take enormous planning and analysis before any design may begin. Planning and analysis are part of the design process. Only after planning, analysis and design should code be written. Of course, you will find syntax errors and they must be corrected. Then you need to test the program again after the corrections and it is quite likely that the program will have logic errors. Logic errors do not prevent the program from running but usually cause the wrong answers to be produced. Because of this, logic errors can 21 3.2. SIMPLE FUNCTIONS be extremely difficult to find. The logic errors will also need to be corrected, which then brings us back to design, where the whole process begins all over again until success is achieved. Success is usually determined by your boss, your client or whether your program sells in the market place. 3.2 Simple Functions Groups of statements which are called from main() or other places and which perform a certain action are called functions. Functions are used for many reasons, some of which are: • Code Reuse • Easier Coding • Facilitates Organization • Enhances Testing • Aids in Development • Encourages Teamwork Coding for Functions Two things must happen to use functions in Python programs. First, the programmer must define the function. This is done with a def statement. Second, the programmer must call the function. Below is an example: # Calling Functions def main (): print ( " Kirk to Spock " ) message () def message (): print ( " No intelligent life found " ) main () See the program and output below in Figure 3.4. Figure 3.4: How Functions Work When the program above is run, the first thing which the Python interpreter does is to locate the def statements and then main(). Main() is usually placed last in Python programs. When the Python interpreter encounters main() it then looks for def main(): and executes the statement print(“Kirk to Spock”). Next it executes the statement message() which causes the Python interpreter to look for def message():. Then the 22 CHAPTER 3. DESIGNING PROGRAMS WITH FUNCTIONS Table 3.1: Python Color Coding Description Keywords Comments String Literals Defined Names Built-in functions Color Orange Red Green Blue Purple Python interpreter executes the statement print(“No intelligent life found”). When main() is encountered the second time, the program ends. When the programmer types code into the editor window, it is colorized by Python as given in Table 3.1. Another feature of the Python editor window is its ability to cause automatic indentation. For example, when you type a : at the end of the line def message(): and immediately press Return you will notice the cursor is indented by exactly 4 spaces. This is because Python expects function code to be segmented into blocks. All the code in the main function or the message function is indented exactly 4 spaces. Python can be a real stickler about code indentations. Improper code indentation is a common pitfall for beginning Python programmers. 3.3 Functions which Return a Value The functions we have seen so far do not return any information back to the calling module. In this section we will learn how to return information back to the calling module or function. A function which returns information back to the calling statement is called a “Value-Returning Function”. Below is a simple example of a value returning function. # Value - Returning Example def main (): number1 = int ( input ( " Please enter your first number : " )) number2 = int ( input ( " Please enter your second number : " )) ans = sum ( number1 , number2 ) print ( " The sum is = " , ans ) def sum ( number1 , number2 ): result = number1 + number2 return result main () When the program above is run, the first thing which the Python interpreter does is to locate the def statements and then main(). When the Python interpreter encounters main() it then looks for def main(): and executes the statement “number1=int(input(“Please enter your first number:”)) and then “number2=int(input(“Please enter your second number:”))”. Next it executes the statement “ans=sum(number1, number2) which causes the Python interpreter to find the function named sum. Notice that number1 and number2 are passed to the sum function. In other words, 17 and 19 were passed into the sum function and the answer 36 was stored into “result” and then returned and stored in the variable “ans”. Next the Python interpreter executes the statement “print(“The sum is =”, ans)” causing the answer to be displayed. Finally, the Python interpreter skips to the main() statement for the second time which ends the program. Variable Scope A variable’s value exists in the function which created it. What this means is that when data is passed to a function, the variable storing the data loses its value while the called function has control of the Python 3.4. INPUT, PROCESSING, AND OUTPUT FUNCTIONS 23 Figure 3.5: Value-Returning Functions interpreter. This can be proved by modifying the program displayed in Figure 3.5. Within the function named “sum” we will change the receiving arguments from number1, number2 to num1, num2, respectively. What happens when we run the program now is that line 9 in the “sum” function now throws an error because it does not know the value of number1, because the variable number1 was created in the “main” function. The solution is to change line 9 in the “sum” function to read “result = num1 + num2”. Now the program executes just fine. See the solution in Figure 3.6. The variable number1 was passed to num1 and number2 was passed to num2. In this case the variables are passed by position in order from left to right inside the parentheses. Because number1 is the first variable in the line “ans=sum(number1, number2) and num1 is the first variable in the line “def sum(num1, num2):”, num1 received the value of 17 in this case. Likewise, num2 received the value of 19 from number2. Figure 3.6: Notice the Different Variables Used for number1 and number2 3.4 Input, Processing, and Output Functions Functions play a key role in program development because they encourage good program organization. We could improve on the design of the program given in Figure 3.6 by organizing the program into three parts besides main. The three parts are: • Input • Processing • Output Take a look at Figure 3.7 to see how the program was reorganized to allow the main function to call each of the three functions from main. The Input function is named getInput. The Processing function is called processing. The Output function is called display. At first glance the program may seem a little more complicated, but actually it is better designed for much greater complexity should the need arise. A few new topics were also introduced in Figure 3.7. First, on line 4 a semicolon was used to allow two lines of Python code to be used on a single line. Second, line 5 makes use of a special case where it is 24 CHAPTER 3. DESIGNING PROGRAMS WITH FUNCTIONS possible to allow more than one variable on the left side of the = so that the program can retrieve the value of both x and y from the getInput function. Also, many of the variable names were substituted with shorter variable names, i.e. x, y, and z. Readers should analyze this program until they are sure they understand the many abstract events occurring within the code provided. In more advanced classes, it is necessary to fully understand this and similar code. Figure 3.7: Input, Processing, Output: A Redesigned Program Formatting Output with the Format Function Nested In Figure 3.8 we see various lines of code which produce the results shown in the IDLE window. Below is a description of what each print statement does. Notice that almost every print statement has the format function nested within the print function. • Line 2 prints “number” with as many places as provided in line 1. • Line 3 prints “number” rounded to the tenths place. • Line 4 prints a message then prints “number” rounded to the tenths place. • Line 5 prints a message then prints “number” rounded to the hundredth place and a total field width of 7. • Line 6 prints a message then prints “number” rounded to the millionth place and a total field width of 10. • Line 8 prints a message then prints “number” rounded to the hundredth place and a total field width of 7 and the argument separator for the print function is “” (null). Figure 3.8: Formatting Output with the Format Function Dealing with Long Lines of Code At times Python programming statements can become very long. It may become necessary to break long programming statements into multiple lines. Most programming languages allow you to break long programming statements into multiple lines and in Python it is accomplished with the line continuation character. The line continuation character in Python is the backslash (\). 25 3.5. EXERCISES For example, consider this line of Python code a2=[‘A’,‘B’,‘C’,‘D’,‘E’,‘F’,‘G’,‘H’,‘I’,‘J’,‘K’,‘L’,‘M’,‘N’,‘O’,‘P’,‘Q’,‘R’,‘S’,‘T’,‘U’,‘V’,‘W’,‘X’,‘Y’,‘Z’] Notice it is very long. We could enter the same information on 4 lines like this: b2=[‘A’,‘B’,‘C’,‘D’,‘E’,‘F’,‘G’,\ ‘H’,‘I’,‘J’,‘K’,‘L’,‘M’,‘N’,\ ‘O’,‘P’,‘Q’,‘R’,‘S’,‘T’,‘U’,\ ‘V’,‘W’,‘X’,‘Y’,‘Z’] Notice the use of the line continuation character, the backslash (\). The following Python code would print a2 and b2 identically: a2=[‘A’,‘B’,‘C’,‘D’,‘E’,‘F’,‘G’,‘H’,‘I’,‘J’,‘K’,‘L’,‘M’,‘N’,‘O’,‘P’,‘Q’,‘R’,‘S’,‘T’,‘U’,‘V’,‘W’,‘X’,‘Y’,‘Z’] b2=[‘A’,‘B’,‘C’,‘D’,‘E’,‘F’,‘G’,\ ‘H’,‘I’,‘J’,‘K’,‘L’,‘M’,‘N’,\ ‘O’,‘P’,‘Q’,‘R’,‘S’,‘T’,‘U’,\ ‘V’,‘W’,‘X’,‘Y’,‘Z’] print(a2) print(b2) Notice that the last line of a multi-line statement does not end with the (\). 3.5 Exercises 1. Write a program that will ask the user to enter the amount of a purchase in a retail establishment. If the sales tax rate is 7.5 percent, the program should calculate and display the amount of the sales tax as well as the total of the sale including tax. The program should have a main function as well as three additional functions, one to handle data input, one to handle data processing and one to handle the display of the answers. (Hint: use .075 to represent 7.5 percent. Also, you may wish to format the two lines in the output function.) Here are a couple of examples: print(“Sales tax....:$”, format(tax,‘7.2f’),sep=“”) print(“Total........:$”, format(total,‘7.2f’),sep=“”) (The format clause was inserted to align the decimals in the output.) ======================================================= The output may look like the following: Please enter the amount of the purchase: 100 Sales tax....: $ 7.50 Total..........: $107.50 2. Write a program that asks the user for the Celsius temperature. The program should use the following formula to calculate the corresponding Fahrenheit temperature. F= 9 5 C + 32 where C is the Celsius temperature and F is the calculated Fahrenheit temperature. Your program should include an input function, a processing function and an output function in addition to a main function. 3. Write a program that asks the user for the gallons of gasoline used and the miles driven. The program should display the number of miles per gallon. Use the formula below: 26 CHAPTER 3. DESIGNING PROGRAMS WITH FUNCTIONS MPG = MD/GG where MD = Miles driven and GG = Gallons of gas used. Your program should include an input function, a processing function and an output function in addition to a main function. Chapter 4 Structures that Make Decisions 4.1 The IF Statement Without the IF statement software would be practically useless. Consider the seatbelt system in your car if it is a fairly recent model. A computer program checks to see if the engine is running, if there is weight in the driver’s seat and if the engine has been on longer than 60 seconds. The pseudo code for the logic of the seat belt system may look like this: if the engine is running if there is weight in the driver’s seat if the engine has been running for at least 60 secconds then ring the bell and flash the seatbelt light on the dashboard. Your car may be somewhat different but you get the idea. The IF statements make the computer in your car begin to have some form of intelligence. Once all the preprogrammed IF statements are true, then the program follows a different course of action, i.e. ring the bell and flash the seatbelt light. Key Concept The purpose of an IF statement in a program is to alter the course of program flow. 4.2 Relational and Logical Operators Table 4.1: Relational Operators Operator > < >= <= == != Meaning Greater than Less than Greater than or equal to Less than or equal to Equal to Not equal to A common mistake for beginning Python programmers is to confuse the use of = with ==. The = is the assignment operator and is used like this: sum = 5 + 2 The value of 7 is assigned to the variable sum. The == is a comparison operator and is used like this: if sum == 7: 27 28 CHAPTER 4. STRUCTURES THAT MAKE DECISIONS print(“The sum is:”, sum) It is very common for programmers to forget to use the == when comparing two entities, but do not worry, most of the time, Python will not allow such a mistake to run. Table 4.2: Logical Operators Operator and or not 4.3 Meaning When connecting a compound expression both subexpressions must be true for the expression to be true. When connecting a compound expression if either subexpression is true the expression is true. Placing the word NOT before an expression reverses the truth of the expression. Boolean Variables A Boolean variable is a variable that only has two values, typically True or False but can be 0 or 1. Programmers like to use some variables as flags. For example, when a certain condition becomes true in one function, it is often very useful to set a flag variable to true. So if the radiator in your car overheats, a flag variable such as “overheated” could be set to True. Now back in the main car dashboard function the “overheated” flag would cause a light to appear on the car dashboard. Flag variables are considered Boolean variables. 4.4 An ATM Machine Consider a simple program allowing you to withdraw cash at the bank teller machine. Once you insert your card, the program asks you for your PIN. The flowchart below shows the course of program flow. Notice the difference depending on the outcome of the if statement: Did the user enter the correct PIN? Figure 4.1: A Simple Decision Structure 29 4.5. THE ELIF STRUCTURE Below in Figure 4.2 is a simple Python program asking the user for their 4 digit PIN. If the user enters the correct PIN then the program will allow the withdrawal, else the program will keep the user’s card and ask them to go into the bank to withdraw the funds and retrieve their card. The program listed in Figure 4.2 works as follows. The PIN from the bank is stored in variable “PIN”. The variable “pin” is initialized to zero. Remember variables spelled the same but capitalized differently are considered distinct variables in Python. The variable “balance” is initialized to the amount the bank has on record. A Boolean variable called “success” is initially set to false. Once the main program is run, the getInput function is executed which retrieves the pin from the user. Next the main function calls the processing function and passes four variables to it. In the processing function, line 16 checks for successful entry of the “pin”. If correct, the Boolean variable “success” is set to True else it is left as False. If the pin==PIN (notice the double ==) then the program asks for the amount the user would like to withdraw and calculates the new balance. Four variables are passed back to main. Main then calls the display function and passes two variables. Depending on the value found in the “success” variable that was passed, the new balance is printed or the user is invited into the bank to make the withdrawal. Figure 4.2: A Simple ATM Bank When using IF statements it is very important to align things properly. For example, Python expects each line of code belonging to the IF block to be indented exactly 4 spaces. The ELSE part of the IF statement is out-dented to be exactly under the IF keyword, but each line of code belonging to the ELSE block is to be indented exactly 4 spaces. Improper code indentation when employing IF blocks is a common pitfall for beginning Python programmers. 4.5 The ELIF Structure As Python programs become more complicated, we find ourselves using more and more IF statements. Many times it is necessary to place IF statements inside other IF statements called nesting. When you end up with many IFs inside IFs it can become unmanageable. One solution is to use a Python structure called ELIF structure. Below are two examples, one using nested IFs and one using the ELIF structure. Although both programs work equally well, by using the ELIF structure we can really reduce the amount of indentations, thus making it easier for humans to understand. Two programs are displayed in Figure 4.3. Both programs are only a partial programs but each one shows how some of the logic of a program written for a typical college level grading scale would look. Notice 30 CHAPTER 4. STRUCTURES THAT MAKE DECISIONS Figure 4.3: Nested IF and ELIF Structure Compared how much easier the ELIF program is to read since it has far less indentations than does the IF structure program. 4.6 Exercises 1. The program listing in Figure 4.2 could be improved in many ways. One way would be to NOT allow the user to withdraw more money than the bank has on record. Modify the processing section of program listing Figure 4.2 such that a user is NOT allowed to withdraw more money than the bank has on record. 2. United States Airlines has several classifications for its passengers. Those who have logged less than 10,000 miles are considered “Class Z” passengers. Those with more than 10,000 miles but less than 50,000 miles are considered “Class C” passengers. Those with more than 50,000 but less than 100,000 miles are considered “Class B” passengers while those with over 100,000 miles are considered “Class A” passengers. Write a program which asks the user to enter the number of miles flying with United States Airlines and places the passenger into the correct classification. Use an ELIF structure when you write the processing function and do not forget to include an input function, a processing function and an output function in addition to a main function.