Python by Example
Introduction
Python is a free, interpreted language with support for Object-Oriented work. If you know matlab, perl or Java you'll have met most of the concepts used by Python. On the teaching system you can run it by opening an XTerminal window and typing /usr/local/apps/anaconda3/bin/python (the default python on the system is Python 2, but we're going to use Python 3). The prompt at the start of the command lines is >>>
This document aims to give you a feel for the language by giving you some sample commands to type in. Without knowledge of perl, Java or matlab, some of the underlying concept might be difficult for you: at the end of this document are some sources of further information.
Variables
You needn't create them and specify their type before assigning values. The following commands work
You can use the print function to see a variable's value. Python has ways of collecting elements together. The elements needn't always be all of the same type
- strings - str="hello"
- tuples - a=(1,"five",2)
- lists - a=[1,"five",2]
- dictionaries - a={1,"five",2}
strings, tuples and lists are ordered sequences (like arrays). strings and tuples are read-only ("immutable"). Dictionaries are sets of key:value pairs. By default the keys are 0, 1, ... in which case the dictionary is like an array, but a dictionary can be like a "map" in Java/C++, so the following will produce "ted"
Assigning a value to a variable sometimes creates a new object, and sometimes creates an alias
gives
If you then do
you'll find that a and b refer to the same underlying object. However if you then do
you'll find that a and b now refer to different objects that have different values - a, a string, is immutable, so a="bar" forced the creation of a new object. Contrast that with the following situation
Here x is a list, so it's "mutable" and can be changed.
a == b will tell you whether the 2 variables have the same value. a is b will tell you whether the variables refer to the same object.
Multiple assignments are possible, with the elements of one list being assigned to another. That makes the following possible
Comparisons
The operators are similar to those in other languages, though note that the following chained expressions have their expected mathematical truth values (in C++ they're legal but the expressions have different meanings)
Operations
All the usual mathematical operations are possible, and much more besides.
The range command creates a list
Slicing operations extract elements from sequences. You give the index of the first element you want (indexing starts at 0) and the index of the first element you don't want. For example
You can replace a slice. Try
You can set alternate elements to particular values. Try
You can remove slices. Try
Conversions
print(4+2) works, so does print("x" + "2"), but
won't work - you'll get something like
You need to convert one of the objects by doing (for example)
The list command converts a string/tuple into a list - useful because a list is mutable. The following converts a string into a list (so that the characters can be sorted in-place), then converts the list back into a string using a member function (to find out what a member function is, see later)
Modules and scripts
So far we've been working from the command line. If on a unix machine you put commands into a file, make the file executable (by typing chmod u+x filename) and put
as the first line of the file, you can run the file (if the python program exists at /usr/bin/python). Comments in a script begin with a #. For some of the longer examples that follow, it's assumed that you'll write a script rather that enter the lines interactively, so the command-line prompt won't always be shown.
python "add-ons" are called modules. You need to "import" a module. For example,
will load a math.py file that's on the system, giving access to sqrt etc.
The sys module lets you provide arguments to scripts. sys module lets you access these arguments. In a script, the following lines will print the first argument given to the script
Functions
To create a function that returns twice what it's given, do
Then a=myfun(3) would set a to 6. Note that indentation is significant - the end of the routine is where indentation ends.
Classes
The objects so far created are objects which have member functions. Here are some examples of use
Dictionary objects have several specialised routines
You can also define your own classes, and inherit from existing classes. The following creates classes called 'foo' and 'fooplus'. __init__ is the constructor (as in C++ and Java). Default values can be set similar to the way they are in C++ - here, num is 3 by default. Note that member functions need to explicitly state which object they're acting upon, but when you call a member function you don't mention the object as a parameter
If a variable is within a class but outside all member functions, then it is shared by all objects of that class.
Control flow
Python has all the usual control flow options - again, indentation is significant
Files
The file-handling commands are similar to other languages
System commands
The os module lets you find out about the computer
Exceptions
Like several other languages (C++, Java, etc), Python lets you use exceptions to deal with errors. The following code works
producing
(Python's print command is behaving rather like C's printf) but if you try
you'll get
If you run the following, you'll see that the error caused by the print command has been detected and a message of your choice has been displayed.
More technically, the print command raised an exception of type TypeError, which the except handler dealt with.
Misc
Info
- More comparisons
- Beginner's Guide
- Scientific Python
- Interfacing with Python
- Extending Python with C or C++
Graphics
- An Introduction to Tkinter - a package for writing graphical user interfaces (based on Tcl/Tk)
- PyX - Python graphics package - for output
- © Cambridge University, Engineering Department, Trumpington Street, Cambridge CB2 1PZ, UK (map)
Tel: +44 1223 332600, Fax: +44 1223 332662
Privacy policy
Contact: helpdesk