Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Introduction to Programming Day 1 Exercises These exercises aim to 1. Explore the concept of programming 2. Introduce you to the tools needed to create and run Python programs 3. Give you practice at writing simple Python programs involving • Input and output • Various primitive data types • Arithmetic expressions Exercise 1: Programming as a Series of Instructions Scenario 1: You are hosting a dinner party and have invited some friends. One of them doesn’t know where you live, and would like directions from the University to your house. Scenario 2: Your dinner party was a great success. One of your friends enjoyed the food so much that she has asked your for a recipe for one of the dinner courses, so that she can try it out herself at home. Pick one of these scenarios and write down the instructions that you would need to give to your friend. Exercise 2: Running Python Code 1. Go to ‘All Programs’ on the Start Menu and navigate the following folder hierarchy: Departmental Software Engineering Computing Anaconda-Python34 You should see a number of items listed. Choose the first item in the list, ‘Anaconda Command Prompt’. When a command window appears, type python and press Enter. You should see text similar to this appear in the window: Python 3.4.1 |Anaconda 2.0.0 (64-bit)| (default, May 19 2014, 13:02:41) [GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> This is the Python shell, also known as the ‘Python interpreter’ or, more rarely, the ‘Python REPL’ (short for ‘read-eval-print loop’). It is an environment in which you can run small pieces of Python code. The >>> is a prompt, at which you can enter a piece of code. Try this now. Type the following at the >>> prompt, then press the Enter key: print("Hello World!") You should see the message “Hello World!” printed. 2. Now try the following. Type each of these lines at the >>> prompt, exactly as shown here, pressing the Enter key after each line: print(42) 42 "Hello World!" type("Hello World!") type(42) 1 + 3 22 / 7 22 // 7 1 Notice that there isn’t much difference between entering print(42) and 42 at the prompt: in the first case, Python calls the print function, which then makes the value appear on screen; in the second case, Python evaluates 42 and displays the result of this evaluation. The difference manifests itself in programs rather than in the shell; in a program, you must use a print statement in order to see any output. You can also see from these examples that the Python shell can evaluate arithmetic expressions—making it useful as a simple calculator. Did you spot the difference between / and // here? Try pressing the ‘Up Arrow’ key a few times, then try pressing the ‘Down Arrow’ key a few times. Notice how you can move backwards and forwards through your input history. After you’ve tried this, terminate the shell by pressing Ctrl+D, then quit the window by entering the command exit. 3. Go back to the Start Menu folder from which you ran the Anaconda Command Prompt. This time, choose ‘IPython (Py3.4)’, the last of three similarly named items in the menu. This should bring up a new window running the IPython shell. IPython enhances the standard Python shell in a number of useful ways. You’ll learn about some of its features later in the course, but for now, try entering the same input that you provided earlier for the Python shell, just to satisfy yourself that IPython behaves in a similar way. Use Ctrl+D to quit. You can use IPython as a replacement for the standard Python shell. From this point onwards, whenever we refer to ‘the Python shell’ in these exercises and in the slides, you can assume that either the standard shell or IPython can be used. The Spyder IDE introduced in the next exercise uses IPython by default. Exercise 3: Creating & Running Programs Whilst the Python shell is suitable for trying out small pieces of code, it cannot be used to create a long-lasting program—largely because there is no way of saving lines of code to disk and later recalling them. A proper Python program should be created in a text file, using a text editor. Simple editors like Windows Notepad will do as a last resort1 , but an editor designed for programming is a better option. Arguably better still is a fullyfledged integrated development environment (IDE), which combines an editor with other useful tools. Anaconda includes an IDE called Spyder, designed specifically for scientific programming using Python. IMPORTANT: before carrying out the steps below, make sure that you have downloaded the course materials to your M: drive, as described in the ‘Getting Started’ section of the course information handout. 1. Run the IDE by choosing ‘Spyder’ from the Start Menu folder for Anaconda. This should bring up a window resembling the screenshot in Figure 1. Spend a minute or two exploring the items on the menus at the top of the window. Hover the mouse pointer over the icons on the toolbar so that you know what they do. Now look at the main body of the window. It is divided into three areas. On the left is a code editor, into which you type your programs. On the right at the top is a panel used for help and for the display of variables used by the program, amongst other things. Below this is a Python shell—IPython, in this case (you use a regular Python shell instead, if you prefer). You can interact with this shell in the usual way. Program input and output will normally take place here as well. 2. Spyder has opened a temporary file for you already, called temp.py. Select all of the file’s current contents using the mouse or by pressing Ctrl+A, then remove the material by pressing the Delete key. In its place, enter the following line of code: print("Hello World!") Now choose File → Save As... and save the program to a file called hello.py, in the Day1 folder that was created earlier when you installed the course files. 3. To run the program, choose Run → Run, or press F5, or click on the ‘green triangle’ button on the toolbar. If a ‘Run Settings’ dialog appears, make sure that the option to ‘Execute in current Python or IPython interpreter’ is selected, then click the Run button. You should see the “Hello World!” message appear in the IPython console. 4. Finally, investigate the ‘Object Inspector’ feature of Spyder. Make sure that this tab is selected in the upperright panel of the window, then click on the keyword print in your program and press Ctrl+I. Some help on the print function should appear in the Object Inspector. 1 Note that word processors such as Microsoft Word cannot be used to write programs, as they do not produce simple text files! 2 Figure 1: The Spyder IDE Exercise 4: Handling Program Input 1. Return to Spyder and your hello.py program. Use File → Save As... to save it as a new file called hello2.py, in the same folder as hello.py. Then modify the code to look like the box below and save by choosing File → Save or by pressing Ctrl+S. # Program to issue a personalised greeting person = input("Who are you? ") print("Hello", person) 2. Run the program. The prompt “Who are you?” will appear in the Python shell and the program will wait for your input. Type your name and press the Enter key. The program should then greet you by name. 3. Click on the Variable Explorer tab. Spyder will tell you that your program defines one variable called person, that this variable is of type str (a string) and that it references a single value. The value will be whatever you entered when you last ran the program. Exercise 5: Using a Module 1. Check that the Object Inspector is selected in the panel at the top-right of the window. Then go to Spyder’s Python shell (normally IPython) and enter import math at the prompt. 2. Type math, followed by a single period character, then press the Tab key. The shell will give you a list of possible completions, showing you all of the things that are available in this module. Use the ‘Down Arrow’ key to scroll down the list until sqrt is highlighted. Press Enter to select it, then press Ctrl+I. Help on what math.sqrt is should appear in the Object Inspector. 3. If you just press Enter at this point, the Python shell will merely tell you that math.sqrt is a function; it won’t actually call that function. To call the function, you must supply brackets and a value. Try it now by entering this: math.sqrt(2) 3 Exercise 6: Computing Square Roots You learned in the previous exercise how to compute square roots with the aid of Python’s math module. Now use Spyder to create a new file named sqrt.py in your Day1 folder. In this file, write a program that prompts the user to enter a number and then displays the square root of that number. You can assume that the user always enters a non-negative numeric value, but when testing your program you should try providing a negative number or non-numeric input to see what happens. Remember: Python’s input function returns a string; you’ll need to use float to convert this string into a suitable number. Exercise 7: Temperature Conversion Use the editor to create a new file named f2c.py in your Day1 folder. In this file, write a program that converts a temperature given in Fahrenheit, TF , into its Celsius equivalent, TC . The relevant conversion formula is TC = 5(TF − 32) 9 The program should prompt the user to enter a temperature in Fahrenheit and should represent this as a floatingpoint value. It should carry out the conversion using the formula above and then display the result. Optional task: write another program in a file named c2f.py that performs the opposite conversion; that is, from Celsius to Fahrenheit. The relevant formula is TF = 9TC + 32 5 If you wish to use the degrees symbol in output generated by your program, you can use the Unicode escape sequence \N{degree sign} to produce it. For example, the code print("\N{degree sign}C") will produce ‘◦ C’ as output. Exercise 8: The Tutorial Group Problem Suppose that a certain university department divides its students into tutorial groups. It is obviously desirable that the groups are all the same size. In a file named tutorials.py, write a program that prompts the user to enter two values: the first is the number of students and the second is the ideal size of tutorial groups. The program should respond by displaying the total number of complete groups that would be formed, and the number of students left over. For example, if there were 100 students in groups of 4, there would be 25 groups and none left over. If there were 100 students in groups of 6 there would be 16 groups and 4 students left over. Obviously only whole numbers of students can be assigned to a tutorial group. You can assume that the user always enters integers. Hint: you need two of the operators listed on Slide 31 to perform the calculations required for this program; alternatively, you can use the built-in divmod function. Exercise 9: Simple Graphical User Interfaces The programs developed in the exercises thus far all have a simple, text-based user interface. It is also possible to create programs with a more familiar graphical user interface. 1. Edit your sqrt.py program from Exercise 6. Use File → Save As and save it as a new file, sqrt2.py. Then change the opening part of this program so that it starts like this: import math, sys from PyQt4.QtGui import QApplication, QInputDialog, QMessageBox app = QApplication(sys.argv) 4 2. Now replace the call to Python’s standard input function with the following: number, ok = QInputDialog.getDouble( None, "Number Input", "Enter a non-negative number", min=0) If the user dismisses the input dialog by clicking OK, then number will be the value they specified and ok will be True; if they dismiss the dialog by clicking Cancel, then number will be the special value None and ok will be False. For simplicity, we will ignore the latter possibility here. Note that this will limit input to one decimal place by default. This can be increased if you wish. For example, if you want to support input to three decimal places, simply add decimals=3 to the list of the getDouble method’s arguments. 3. Now use the information method of the QMessageBox widget to display the results of the calculation. This expects a string, so you will first need to construct this string. You can do this by concatenating smaller strings using + and by converting any numbers into strings with the str conversion function2 . For example, if your number and the result of the calculation are variables called number and root, respectively, then something like the following would do what you need: text = "Square root of " + str(number) + " is " + str(root) QMessageBox.information(None, "Result", text) 4. This program uses Qt to provide the graphical user interface, but Spyder itself also uses Qt. To avoid possible interference between Spyder and the program, you need to run it in a slighly different way. Make sure that the program is active in the code editor and then choose Run → Configure or press F6. In the resulting dialog, choose ‘Execute in a new dedicated Python interpreter’, then click OK. Spyder will remember these settings for this program. Now run the program in the usual way, via the Run button on the toolbar or by pressing F5. A new tab will appear in the panel at the bottom right, representing the program running in a separate Python environment. You should also see a dialog appear, prompting you for input (see Figure 2). Figure 2: Dialogs used by sqrt2.py Note: after running the program in this way, you can return to IPython by clicking on the ‘IPython console’ tab at the bottom of the panel. Exercise 10: Formatted Output You may have noticed that the output generated by sqrt.py, sqrt2.py and f2c.py can have more decimal places than we might normally wish to see. We can take control over formatting of output to change this. One approach is to use a built-in function called format. This function is called with a value to be formatted and a format specification describing how it should be formatted. 1. To gain an understanding of how format works, enter the following sequence of commands in the Python shell, one line at a time, noting carefully what happens in each case. pi = 3.14159 format(pi) format(pi, 'f') format(pi, '9f') format(pi, '12f') format(pi, '.4f') format(pi, '.3f') format(pi, '8.4f') format(pi, '.3e') format(0.0024, '.3e') 2 Note that there are better ways of doing this, which we will discuss tomorrow! 5 You should have learned from this that • Format specification f will format a floating-point value with a default of six decimal places • Prefixing f with a number allows you to control how many characters are used to display the floatingpoint value, with spaces being used as padding • Prefixing f with a number after a decimal point allows you to control the number of decimal places used to display the floating-point value • Using e instead of f gives you ‘scientific notation’ (e-03 in the resulting string means ×10−3 ) 2. Edit sqrt2.py and save it as a new file named sqrt3.py. In this new file, modify the code that creates the text displayed by QMessageBox so that it uses format to limit the number of decimal places to something sensible (e.g., four). More? If you finish early, try one or more of the following: • Modify the f2c.py program so that it uses the format function to restrict the display of Celsius values to two decimal places. • Investigate the math module further and write a program that uses some of the other functions that it defines. You could write a program to compute a formula relevant to your research, but if you can’t think of something appropriate, try the following, which gives the range R of a projectile launched with velocity v at angle θ to the horizontal: 2 v sin 2θ R= g (g here is the acceleration due to gravity, 9.81 ms−2 ) • Investigate Python’s random module (http://docs.python.org/3/library/random.html), in particular its randint function, then write a program to simulate the rolling of a pair of six-sided dice. Have your program output the score on each die and the total score for both. 6