Python: Introductionfor Absolute BeginnersBob DowlingUniversity Computing ServiceScientific computing support email address:[email protected] course is is the UCS three afternoon course on Python for people who have no experienceof programming at all. We warn all those people who do have some programmingexperience and who are here just to add the Python notch to their bed post that theywill be excruciatingly bored in this course. Those people who do already know how toprogram in another language and want to learn Python are better off attending theUCS “Python: Introduction for Programmers” one day course. For details of thiscourse, see ote that the UCS Python courses cover Python 2.4 to 2.6, which are the mostcommon versions currently in use – it does NOT cover the recently released Python3.0 since that version of Python is so new. In some places Python 3.0 is significantlydifferent to Python 2.x, and this course will be updated to cover it as it becomes morewidely used.The official UCS e-mail address for all scientific computing support queries, includingany questions about this course, is: [email protected]
Course outline — 1IntroductionWho uses Python?What is Python?Launching PythonUsing Python likea calculatorTypes of valueNumbersTextTruth and FalsehoodPython values2So what will this course cover?We will start with a brief introduction to Python, looking briefly at what it is used for andhow we launch it on the systems being used for this course.Once we have it running we will start by using it as a glorified calculator to get us usedto its features. We will examine how it handles numbers, text and the concept of astatement being true or false.
Course outline — 2Using Python likea programminglanguageWe will dolots with lists.Variablesif then else while loopsCommentsListsfor loopsFunctionsTuplesModules3But Python is there for us to use as a programming language so, after spending awhile using it as a manually operated calculator, we will start to use it as a fully-fledgedprogramming language.As part ofd this we will look at how Python stores values and assigns names to thesestored values. We will look at the three fundamental constructs that will allow us tobuild programs that actually do something. (“if then else ”, “while loops”, and“for loops”)We will also spend a lot of time looking at how Python handles lists. There are tworeasons for this. First, Python uses lists a lot so we need to understand them. Second,Python lists are the first example of a computer data structure that doesn't have anyanalogue in the usual arithmetics.Then we will look at writing our own functions that use what we have learnt. Functionspermit us to structure our code in a more maintainable fashion. We will look at howPython groups related functions together and what groups of functions is providesready-made. These groups are called “modules” in Pythonic language.
Course outline — 3Interacting withthe outside worldBuilt-in modulesThe “sys” moduleReading inputFilesStoring datain programsDictionaries4Once we know the rudiments of programming in Python we will look at the supportfunctions offered by the base Python system. These will let us access the systemoutside of Python. The main example of this will be accessing the file system.Finally we will look at one last, very powerful mechanism for storing data, the“dictionary”.
What is Python used for?Network servicesWeb applicationsGUI applicationsCLI applications/usr/bin/command-not-foundScientific librariesInstrument controlEmbedded systems5I want to start by convincing you that learning Python is worthwhile. Python is used forevery scale of operation. Here is a spectrum of examples running from the largest tothe smallest.The Massively Multiplayer Online Role-Playing Game (MMORPG) “Eve Online”supports over 300,000 users with a Python back ne-196Two very common frameworks for web applications are Django (general purpose) andPlone (content management). Both are implemented in Python.www.djangoproject.complone.orgOn the desktop itself there are frameworks to build graphical applications in Python.The two standard Unix desktop environments are called GNOME and Qt. Both havePython support. There is similar support under Windows and here are plenty of command line programs written in Python. Some Unixes(e.g. OpenSUSE) have a helper program they call when the user asks for a commandthe shell doesn't know. That helper program is written in Python.Within programs there are support libraries for almost every purpose including a verypowerful scientific python library called “SciPy” (“Sigh-Pie”) and an underlyingnumerical library called “NumPy”.www.scipy.orgPython is also used to control instruments (a simple robot is featured in the slide) andis also used in embedded systems. The card shown is ““ IEEE802.15.4 based, autoforming, multi-hop, instant-on, mesh network stack combined with an embeddedPython interpreter for running application code.”synapse-wireless.com
What is Python?CompiledFortran,C, C InterpretedJava,.NETPythonPerl Shell6Languages split into two broad camps according to how they are used, though it isbetter regarded as a spectrum rather than a clean split.Compiled languages go through a “compilation” stage where the text written by theprogrammer is converted into machine code. This machine code is then processeddirectly by the CPU at a later stage when the user wants to run the program. This iscalled, unsurprisingly, “run time”. Fortran, C and C are examples of languages thatare treated in this way.Interpreted languages are stored as the text written by the programmer and this isread by another program, called the interpreter, typically one line t a time. The line isread and parsed by the interpreter which then executes any instructions required itself.Then it moves on to the next line. Note that the interpreter is typically a compiledprogram itself.There are some languages which occupy the middle ground. Java, for example, isconverted into a pseudo-machine-code for a CPU that doesn’t actually exist. At runtime the Java environment emulates this CPU in a program which interprets thesupposed machine code in the same way that a standard interpreter interprets theplain text of its program. In the way Java is treated it is closer to a compiled languagethan a classic interpreted language so it is treated as a compiled language in thiscourse.Python can create some intermediate files to make subsequent interpretation simpler.However, there is no formal “compilation” phase the user goes through to create thesefiles and they get automatically handled by the Python system. So in terms of how weuse it, Python is a classic interpreted language. Any clever tricks it pulls behind thecurtains will be ignored for the purposes of this course.
What is Python?Source of program?Typed “live”Read from a file“Interactive”“Batch” mode7So, if an interpreted language takes text programs and runs them directly, where doesit get its text from? Interpreted languages typically support getting their text eitherdirectly from the user typing at the keyboard or from a text file of commands, oftencalled a “script”.If the interpreter (Python in our case) gets its input from the user then we say it isrunning “interactively”. If it gets its input from a file we say it is running in “batchmode”. We tend to use interactive mode for simple use and batch for anythingcomplex.
Launching Pythoninteractively ― 1Applications Unix Shell GNOME Terminal8To launch a terminal window to type commands into launch the GNOME Terminalapplication from the menu system:Applications Unix Shell GNOME TerminalIn the Unix command line interpreter we issue the command to launch the Pythoninterpreter. That command is the single word, “python”.In these notes we show the Unix prompt, the hint from the Unix system that it is readyto receive commands, as a single dollar character ( ). On PWF Linux the prompt isactually that character preceded by some other information.Our other convention in these notes is to indicate with the use of bold face the text thatyou have to type while regular type face is used for the computer’s output.
Launching Pythoninteractively ― 2Unix promptUnix command pythonPython 2.6 [GCC 4.3.2 Type "help", Introductory blurb Python promptBold facemeans youtype it.9At the Unix command line interpreter we issue the command to launch the Pythoninterpreter. That command is the single word, “python”.In these notes we show the Unix prompt, the hint from the Unix system that it is readyto receive commands, as a single dollar character ( ). On PWF Linux the prompt isactually that character preceded by some other information.Our other convention in these notes is to indicate with the use of bold face the text thatyou have to type while regular type face is used for the computer’s output.The interactive Python interpreter starts by printing three lines of introductory blurbwhich will not be of interest to us. For completeness what they mean is this:1.The version of Python this is.2.The version of the C compiler the interpreter was compiled with.3.A few hints as to useful commands to run.After this preamble though, it prints a Python prompt. This consists of three “greaterthan” characters ( ) and is the indication that the Python interpreter is ready for youto type some Python commands. You cannot type Unix commands at the prompt.(Well, you can type them but the interpreter won’t understand them.)
Using Python interactivelyPython functionBracketsFunction argument print('Hello, world!')Hello, world!Function result Python prompt10So let’s issue our first Python command. There’s a tradition in computing that the firstprogram developed in any language should output the phrase “Hello, world!” and wesee no reason to deviate from the norm here.The Python command to output some text is “print”. This command needs to befollowed by the text to be output. The information that is passed to the function like thisis called its “arguments”. In our case there is only one argument. Arguments arepassed in brackets to group them together.(Actually, in Python the print function is a special case for historical reasons, anddoesn't seed the brackets. However, this special exemption is scheduled for removalin the next version of Python so we encourage you to get in the habit of using themfrom the start.)The text, “Hello, world!” is surrounded by single quotes (') to indicate that it should beconsidered as text by Python and not some other commands or Python keywords.The command is executed and the text “Hello, world!” is produced. The printcommand always starts a new line after outputting its text. Note that the quotes wereused to indicate to Python that their contents were text but they are not part of the textitself so are not printed out as part of the print command's output.Once the command is complete the Python interpreter is ready for another commandso prompts for it with the same triple chevron (“greater than” sign) marker, “ ”.Note that everything in Python is case-sensitive: you have to give the print commandall in lower-case; “PRINT”, “pRiNt”, etc. won’t work.
Using Pythoninteractively print(3) Instruct Python to print a 33Python prints a 3 5Give Python a literal 55Python evaluates and displays a 511We will continue in our use of this interactive python session.We issue a trivial command: print(3)and Python faithfully prints the number3to the terminal.If, however, we just type a bare number: 5then Python evaluates whatever it has been given and also outputs the result of thatevaluation:5Then Python prompts for more input.There is a subtle difference in the two behaviours. In the first case we explicitly toldPython to print a value. In the second we gave it a value and it responds, essentiallysaying “yup, that's a 5”.
Using Pythoninteractively 55 2 3Give Python an equivalent to 55Python evaluates and displays a 512We can take this further. We will meet numbers shortly but note for now that the“evaluation” need not always be trivial. We can use Python to evaluate expressions.
Using Pythoninteractively print('Hello, world!')Hello, world!No quotes 'Hello, world!''Hello, world!'Quotes13The difference is more explicit if we use text rather than numbers.In the first case we use the quotes to mark their content as text. When we ask Pythonto print some text it prints just the text itself without any syntactic markers. So the printexample has no quotes in its output.In the second case we hand this text object to Python and it says “yup, this ia a textobject containing this sequence of characters. The way it indicates that it is a textobject is by enclosing it in quotes. It uses exactly the same marker as we did.
Quitting PythoninteractivelyPython prompt [Ctrl] [D]Unix “end of input” Unix prompt14Now that we know how to get into Python we need to know how to get out of it again.In common with many Unix commands that read input from the keyboard, the programcan be quit by indicating “end of input”. This is done with a “[Ctrl] [D]”. To getthis hold down the control key (typically marked “Ctrl”) and tap the “D” key once.Then release the control key.Be careful to only press the “D” key only once. The [Ctrl] [D] key combination,meaning “end of input” or “end of file”, also means this to the underlying Unixcommand interpreter. If you press [Ctrl] [D] twice, the first kills off Pythonreturning control to the Unix command line and the second kills that off. If the entireterminal window disappears then this is what you have done wrong. Start up anotherwindow, restart Python and try again.If you are running Python interactively on a no
Using Python like a programming language We will do lots with lists. But Python is there for us to use as a programming language so, after spending a while using it as a manually operated calculator, we will start to use it as a fully-fledged programming language. As part ofd this we will look at how Python stores values and assigns names to these stored values. We will look at the three ...