Python Part 1(1) - Lecture notes 1-3 PDF

Title Python Part 1(1) - Lecture notes 1-3
Author Abdul Quaiyoum
Course Visual Programming
Institution London Metropolitan University
Pages 54
File Size 1.4 MB
File Type PDF
Total Downloads 62
Total Views 148

Summary

Python in very easy steps...


Description

London Met – FLSC - SoC BSc Extended Degree Programme CS3101 Programming

Python Programming Notes – Part 1(of 3) CHAPTER 1: INTRODUCTION.......................................................................................1 1.1 COMPUTERS REVISITED.................................................................................................1 1.2 PYTHON.........................................................................................................................2 1.3 THE FIRST PRACTICAL SESSION.....................................................................................4 1.4 COMMENTS....................................................................................................................9 1.5 OUTPUTTING TEXT AND NUMBERS.............................................................................11 1.5 FINDING MISTAKES IN PROGRAMS...............................................................................13 EXERCISES.........................................................................................................................14 REFERENCE.......................................................................................................................16 CHAPTER 2: PROGRAMS THAT ACCEPT INPUT....................................................18 2.1 PROGRAMS THAT INPUT INTEGERS..............................................................................18 2.2 PROGRAMS THAT INPUT STRINGS................................................................................20 2.3 A STRING IS NOT A NUMBER........................................................................................23 REFERENCE.......................................................................................................................25 CHAPTER 3: USING NUMBERS....................................................................................28 3.1 PROGRAMS WITH CONSTANTS.....................................................................................32 3.2 MORE ABOUT INTEGERS: THE OPERATORS / AND %....................................................34 3.3 FORMATTING FLOAT OUTPUT TO A FIXED NUMBER OF DECIMAL PLACES...................36 CHAPTER 4 DECISIONS IN PYTHON.........................................................................39 4.1 CONDITIONAL EXECUTION – THE IF…ELIF…ELSE STATEMENT.........................39 4.2 TWO WAY DECISIONS...................................................................................................43 4.3 MULTI-WAY DECISIONS...............................................................................................44 4.4 USING THE LOGICAL OPERATORS AND AND OR.......................................................46 REFERENCE.......................................................................................................................50 APPENDIX 1.......................................................................................................................53 MODULE SPECIFICATION...........................................................................................53

Chapter 1: Introduction This booklet is a companion to the lectures and the tutorials: it covers all of the basic material that you will need to succeed in the course. Each chapter contains the material for approximately one week. Throughout the text there are exercises that you are expected to do during the tutorial/lab session; some require you to write or modify programs; others require you to write in this booklet. Any exercises that you do not complete should be finished before the next lecture. At the end of the chapter there may be a reference section; you normally do not need to read this before going to the lecture or doing the exercises. However, you should read these sections before going onto the next chapter. Before each lecture session you should read the relevant chapter of the booklet so that you are familiar with the topic that is going to be covered. You will not need to do the exercises before the lecture or read the reference section.

1.1 Computers Revisited By now you will be familiar with using a computer even if you have never programmed one. So you know basically what a computer is; that it basically consists of a processing unit and peripherals for communicating with the central processor, e.g. a screen, keyboard and mouse for the user to operate the computer; a printer to get hard copy; a network card or modem to connect the computer to the internet or other network. You also know, at least, the basics of computer architecture, and will be familiar with some computer application programs such as a word processor database or spreadsheet program. A programmer needs to know a little about the inner workings of a computer, so you ought to be able to understand when we refer to computer memory or the (micro) processor that is the brain of a computer. If you are not comfortable with these ideas then you should revise the material from previous modules before going too far with this one. There are many definitions of a modern computer but one is “a machine that stores and manipulates data to provide information under the control of a computer program”. So, for example, a word processor is a computer program that allows the user to type in and manipulate text. This text can then be saved as a file to the hard disk or printed. You won’t be writing programs as complicated as a word processor in this module but, by the end of it, you might be able to appreciate the sorts of techniques that programmers use to write these large and highly complex programs.

Programming Languages A computer program is a series of instructions telling the computer what to do. There are many different programming languages that can be divided into two main types. Low level languages are difficult to write, understand and change. Low level languages are normally specific to a particular microprocessor (e.g. the Intel Pentium series) and the instructions that the programmer writes are very much to do with the architecture of the particular microprocessor. You may have heard of machine code, which is the language that the microprocessor understands directly and is written as binary numbers (i.e. a whole load of ones and zeroes). Another low level language is assembly language which is very close to machine language but is written in numbers and characters that humans can more easily understand and remember.

0

High level languages are intended to look more like English and are generally independent of any particular microprocessor. Examples include Pascal, C, C++, Visual Basic, Delphi, Java and Python. High level languages must be translated into machine language (binary code) before the computer can run or execute the program. (To run or execute the program means to carry out the instructions inside the program.) When a program is written in a high level language what the programmer writes is called source code. After it is translated into the machine code for a particular computer, it is called object code. Apart from the fact that it is much easier to write complex programs in a high level language, it also makes these programs more portable. What this means is that the same source code can be translated into the object code for a number of different computers. It is a computer program that does the translation from source to object code, of course. There are two different types of program that can carry out the translation process from source to object code: they are called compilers and interpreters. A compiler is a complex computer program that takes the whole of another computer program, the source code, and translates it into machine code. The resulting machine code can then be run on a computer separately from the original source code and the compiler. An interpreter is also a complex program that translates and runs the source code one line at a time. Programming languages that use an interpreter can be run interactively which allows a more flexible development environment. Python uses an interpreter.

1.2 Python Python is a high-level language that is fairly easy to get started with but also incorporates all of the features that you will find in the most powerful languages such as Java or C++. Python was created by Guido van Rossum and named after the comedy team Monty Python’s Flying Circus; because of this you will often find references to Monty Python in various documents and tutorials concerned with Python. Python is Open Source software: this means that it is free to use and distribute – you could even sell it (if you could find someone foolish enough to buy something that is normally free!). This is a very short introduction to Python but for those who are interested a lot more information can be found on the Python web site (www.python.org). You can also download the latest version of Python from the Python.org web site. One of the reasons for choosing Python for this module is that it is used in industry and so is more relevant to real life than some other languages that are used for teaching. Many companies use Python including Google (the search engine), Industrial Light and Magic (who produce special effects for many films including the Star Wars series, Pirates of the Caribbean and The Day After Tomorrow) and NASA (the North American Space Agency). On the other hand Python is also fairly simple and easy to learn unlike some of the other industrially relevant languages that are also used for teaching.

IDLE IDLE is the Integrated Development Environment (IDE) that comes as part of the Python package. An IDE is rather a grand name for what is effectively an editor for writing programs that allows you run the programs as well as edit them. Some IDEs for languages such as Java, are incredibly sophisticated, complex and difficult to learn. There are more

1

complex IDEs available for Python, too, but IDLE is a very simple IDE and thus suitable for beginners. IDLE has two windows: the editor window and the Python Shell window. The editor window speaks for itself; it is a simple editor similar to Notepad. The editor has some features specific to the Python language the most obvious of which is syntax highlighting: this means that the different parts of the program are coloured differently and this helps the programmer more easily spot any typing errors that s/he may have made. Here is a screenshot of the IDLE editor window1.

You will notice that the blue titlebar shows the name “Untitled”. This means that the file that is being edited has not been given a name and saved. In the screenshot above, the window is empty and ready for the programmer to either start typing a Python program or open an existing one. The Python Shell window is where the programs run; where the user will enter any data that the program uses and where output from the program is displayed on the screen. (The word shell is commonly used in Unix to mean an environment in which a particular programming language is used). A screenshot of the Shell window is shown below. You can see that the window contains a fair amount of text. This is how the shell normally starts and the text that you see tells us the version of Python that we are using (in this case version 2.5) and the date it was released. It also tells us that we can get more information by typing “copyright”, “credits” or “license()”. This is followed by a warning about personal firewall software (i.e. you may get a warning from your computer if you have such software installed but you shouldn’t worry about it). The last thing you see is “IDLE 1.1”, which is the version of IDLE that we are using, followed, on the next line, by “>>>”. These chevrons are a command prompt. You can type Python commands here as well as the ones mentioned above, such as “copyright”. These commands will be executed by the Python shell and the results displayed in the shell window.

1

Note that, for our illustrations, we have made the Python windows smaller so that they fit nicely into this booklet. The ones you see will normally be larger.

2

When you write a new program the sequence of events is like this: you type in the program code into the editor window; you then save the program giving it a file name of your choice (but one that should end with the extension .py); you then run the program. Running the program opens the Python shell window. When you start IDLE only one window opens. By default, this is the Python Shell. To begin programming you need to open the editor window by choosing New Window from the Python Shell File menu. From the editor window you can choose to Open an existing file, or type in a new one.

1.3 The first practical session For each of the practical sessions you will need copies of the programs that your tutors have written. So the first thing to do is get hold of a copy of the CS0002 supplementary sheet Week 1 Getting Started from your tutor. This tells you how to copy the Python example files from the server to your home directory. Once you have completed this sheet you should already have created the following directory structure… X:\ My Documents\CS0002\Python\Exercises\ …and copied the files into it from the server (your tutor will give you instructions on how to do this). You might like to copy these files to a floppy disc if you want to use them at home, although we aim to make them available via the module web site, too.

Programs that output text and numbers. Open IDLE and make sure that you are in the editor window. Next type the following into the editor print “Hello, world!”

This is not very large but it is a complete Python program. You can probably guess what it does. You can see how this should look in the screen shot below.

3

Next run the program by clicking on Run > Run Module on the menu bar. You will be prompted to save your work (if you have not saved it already), with the following dialogue box

Click OK and the Save As box will appear on the screen (see below). You should set the path to the folder you want to save the file to by using the drop down menu in the Save in: pane. You learnt to organise your work last semester and you should be saving to the path X:\ My Documents\CS0002\Python\Exercises

4

Type hello.py into the File name: pane as shown above then Click on Save. N.B You must include the extension (.py ). Python does not include this for you automatically. Remember that you should also back up your work onto a floppy disk or zip drive. Having saved the program, it will now run and you will see the Python Shell program that has interpreted and run your program as shown below.

5

There is a lot of text in the output window above the line labelled RESTART. This is displayed whenever the Python Shell is started and it describes the version of Python and IDLE you are using. Below this Python has executed your first program by carrying out the first (and only) instruction, which is to display Hello, world!

on the screen in the Python Shell window. Notice that the word ‘print’ does not appear in the output as this is the instruction to output text to the screen. The text that it will display on the screen is enclosed in quotes after the word ‘print’, that is, “Hello, world!”. This text is composed of characters and is known as a string of characters. Click on the cross on the top right of the Python shell window to close the window.

Running an existing program. Open IDLE (if it is not already open) and in the editor window click on File > Open. A window will be opened that looks something like the following screen shot.

You will need to set the Look in: pane at the top of the screen to the folder where you have saved the exercise files. (Note that in the screenshot the folder where the exercise files are kept is different to the one you will use, as it was not taken from a student machine.) Double click with the left mouse button on the file hello2 to load the program. Hello2.py will be loaded into the editor.

6

print print print print print print print print print print print

"i\/\/\i" "| |" "| |" "| (o)(o)" "C _)" "| ___|" , " "| /" "| /"

Hello world!"

This is a more interesting version of the original hello.py program. Click on Run > Run Module to run the program. (Notice that you are not prompted to save the file, this time, because it is already saved. If you were to change it in any way, however, you would be prompted to save it before running it.) Go back to the editor then click on File > New window. This will open a new window for you to try out a new program.

A nursery rhyme Open the program, Humpty.py, into the editor. print print print print

"Humpty Dumpty sat on a wall" "Humpty Dumpty had a great fall" "All the king's horses and all the king's men" "couldn't put Humpty together again"

Run the program by clicking on Run > Run Module. When the Python interpreter runs this program it first sees the line print "Humpty Dumpty sat on a wall"

so the computer displays on the screen Humpty Dumpty sat on a wall

It then moves down to the next line of the program and sees print "Humpty Dumpty had a great fall"

so the computer displays on the screen Humpty Dumpty had a great fall

The interpreter keeps looking at each line of the program in sequence carrying out each print instruction and then goes on to the next line. This is called sequential execution of the lines of code. Each line of code is called a statement. It is the Python interpreter that looks at each statement, interprets the statement and then goes on to the next statement.

7

Modify the program by adding a comma to the third line as follows: print "All the king's horses and all the king's men",

Save the modified program as Humpty2.py by clicking on File on the drop down menu. Click on Save As and enter Humpty2.py. Now run Humpty2.py Note how the output differs from Humpty.py. If you are not sure what difference adding that comma has had, ask your tutor. Now modify Humpty2.py by adding two more print statements as follows: print print print print print print

"Humpty Dumpty sat on a wall" "Humpty Dumpty had a great fall" "All the king's horses and all the king's men", "couldn't put Humpty together again"

Save the modified program as Humpty3.py and run it. Note how the output differs from Humpty2.py. If you are not sure what difference adding the two extra print statements has had, ask your tutor.

Your favourite song Write a program to output a few lines from your favourite song to the screen inside the Python shell. You will need to use the print command for each line of the song. Be careful that you do not spell print with an uppercase P as in Print. Python commands are case sensitive. Typing Print or PRINT will generate an error message. Make sure you remember to place quotation marks (“ ”) around the text you want to output. Save the file as song.py and then run the program.

1.4 Comments Comments are text within a program that are there to document it. They are not involved in the execution of a program. Indeed, the Python interpreter completely ignores them. However, they are very useful in documenting who wrote the program, when they wrote it and, in complex programs, how the program works. Professionally written programs are expensive to produce. If a modification is required to one, then good comments in a program can make it easier for the programmer to find the correct place to make the necessary change. By the way, it is said that, normally, it costs more to maintain a program (i.e. fix bugs in it and make other necessary changes) than it costs to write it in the first place!

8

Open the following program, comment.py, in IDLE and then run it. # comment.py # Displays an important message # Dave Howells, 10th November 2004 print “programs with useful comments are awarded extra marks” prin...


Similar Free PDFs