Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
 
Python and Tcl - public course schedule [here]
Private courses on your site - see [here]
Please ask about maintenance training for Perl, PHP, Lua, etc
 
Python Fast Start

What is Python, versions, implementations

WHAT IS PYTHON?

Python is a "compile and run" language. Source code is compiled from English-like text into an internal binary format, which is then run by an engine sometimes referred to as a virtual machine. This is different to a "scripting language" where each statement is interpretted from text each time it is run - and it's much faster to run where program loops are involved as there's no need for the code to be interpretted each time.

Python goes further too. Programs typically comprise a main section in one file, and code that's shared between programs in other files. When the main section calls in those other sections, the internal binary format is saved to disc so that it can be loaded by subsequent runs of any program withou the need to reconvert it from text to binary. Timestamp checking on files eliminates ensures that if a text file at a "lower level" is changed, the interprettation from text to binary is repeated. Subsidiary files are searched for though a series of directories on a path, which are typically configured to look at user-specific code, site-specific code, python version specific code, and then truely common code in turn.

Python is an OBJECT ORIENTED language. That's something we'll keep coming back to all through the course, and explain in detail. It's sometimes referred to as "data driven programming" where the programmer first looks at the data he/she is using and writes the code to handle that data, rather than as writing a program starting from the premise of "what do we want to do". It makes for a sound foundation of reusuable code sections which can easily be shared between a number of preograms all of which handle the same data types, it makes for code which is naturally structured to make testing of individual sections much easier, and it makes for code which is much easier to maintain too.

This sharing of code goes further too. As a programmer, you can take a "class" that does almost exactly what you want, and write a file of changes that define just the differences that you need - that's much more efficient that rewriting the whole thing, and as you're not cuttting and pasting you're not going to have to repeat the work if the class on which you've based your code - the "base class" is changed. Looking further still, this natural interface between your code that's specific to a single program, your other code, your organisation's common code and common code out there worldwide has lead to central repositories of code being available such as the Python package index (pypi) at http://pypi.python.org/pypi .

Some programming languages are eclectic - written with lots of facilities from lots of places, and are designed to be as terse - short - as possible. Python is NOT one of those. Although the code is surprisingly short most of the time, the language framework is a simple one and it's one which was very cleverly designed to encourage good, readable, maintainable and reusuable code, sometimes at the expense of a few more bytes of source.

Python is open source - free at the point of distribution, and free to use too in yor own / your company's work. It is NOT public domain, so you don't have "carte blanche" to do whatever you like with it. More technically, it's distributed under a "GPL compatible" license - in other words you can do anything that's allowed under GPL but with additional freedoms. A note on the current license page (http://docs.python.org/license.html) explains

</i>Note GPL-compatible doesn’t mean that we’re distributing Python under the GPL. All Python licenses, unlike the GPL, let you distribute a modified version without making your changes open source. The GPL-compatible licenses make it possible to combine Python with other software that is released under the GPL; the others don’t.</i>

The author of this course is NOT a lawyer - please check with an appropriately qualified person if you have any doubts as to the lagallity of your use of Python.

VERSIONS

Python originated in 1988, I am told. Think back to decisions YOU made in 1988, and they may have been good ones at the time. But it's likely that a good decision such as "which camera would I buy" made NOW would come up with the same model. And it's the same thing with programming languages too. Python is much better than other languages in this respect. Because it started out with a simple and forward looking framework, its issues as regards modernity are not great, and it's far more fine adjustments that rewrites of the core that are needed. It's been good for coming up for 25 years, but a few tweaks are needed (and have been applied) to make it good for the next 25 years too. And a few of those do lead to changes in the source code - "incompatabilities" you may call them, although tools are provide to help in the transition.

<b>Python 2.0i</b> originated in 2000. Versions have moved up 2.1, 2.2 etc to 2.7, with subreleases such as 2.7.1 and 2.7.2

During the life of Python 2, features and facilities have been added such as generators, new style classes and decorators (the full list would be a long one). Some elements have been deprecated - i.e. they remain, but their use is no longer encouraged and you're given fair warning that they'll be removed at a future date.

<b>Python 3.0</b> was released at the end of 2008. Version have moved up 3.1 and 3.2, with subrelesases such as 3.2.1

Python 3 is not an instant replacement for Python 2. Some deprecated elements have been removed, and some features have been moved around / renamed / redesigned to reflect changes 20 years on from the original Python. And that means that the program sources is not compatible. Which is to be regretted in the short term, but applauded in the longer term. And a utility - "2to3" is provided to help you.

The switch from Python 2 to Python 3 by users will be a slow one. There are so many modules written using Python 2 that need to be converted, and with things like numpy that's major work, I understand. And there are so many computers out there, so many distributions loaded with Python 2 that it would be a very brave author of an open source product that specified "Python 3" for quite a long time. So we're seeing a gentle drift rather than a calamitious switchover. Indeed, Python 2.7 was a new release of Python along the "2" track long after Python 3.0, so the Python folks themselves are in total support of this gentle drift.

IMPLEMENTATIONS

Python runs on many platforms. Implemented internally in the C language, it's a standard part of Linux. You'll find it as standard in virtually every modern Unix too, such as Mac OS X, and it's freely and easily available (but not supplied as standard) with Windows operating systems from Microsoft. This version is sometimes referred to as <b>CPython</b>

Both source code and interbnal binary code can be transferred between systems / operating systems with ease for the most part - indeed, I'm happy to teach Python to a mixed classroom running Windows, Unix and Linux systems. The biggest differences relate to the environment on the computers - which editors to use, and where the Python 'interpretter' is located. Code wise, the following should be noted:

a) If you call a method to say "go run this operating system command", you had better be running your Python on a computer that supports the command

b) Methods in the os and os.path modules may be called cross-platform, but the modules themselves (os.pyc and friends) have to be implemented on a system by system basis; this is how Python provides the ability to support things on different operatings systems as far as the regular programmer is concerned

An open sourcedownload - "py2exe" - provides the tools that allow you to bundle all the necessary Python components into a single file with your own program, so that you can distribute Python executables on Windows systems without having to ensure that Python's also installed on the target computers.

<b>Jython</b> (formerly <b>JPython</b>) is an implementation of Python to run on the Java Platform (Java Virtual Machine). It consists of a compiler to compile Python source code down to Java bytecodes which can run directly on a JVM, a set of support libraries which are used by the compiled Java bytecodes, and extra support to make it trivial to use Java packages from within Jython.

There are a number of differences between Python and Jython . First, Jython programs cannot currently use CPython extension modules written in C. These modules usually have files with the extension .so, .pyd or .dll. If you want to use such a module, you should look for an equivalent written in pure Python or Java. This may be fixed in a future release, but there are a number of other differences between the two implementations that are unlikely to go away. These range from the trivial - Jython's code objects currently do not have a co_code attribute because it is not possible to directly access Java bytecode from a class, without loading the file; to the significant - Jython uses Java's true garbage collection rather than Python's reference counting scheme.

<b>IronPython</b> is an open-source implementation of the Python programming language which is tightly integrated with Microsoft's .NET Framework. IronPython can use the .NET Framework and Python libraries, and other .NET languages can use Python code just as easily. IronPython is an excellent addition to the .NET Framework, providing Python developers with the power of the .NET framework. Existing .NET developers can also use IronPython as a fast and expressive scripting language for embedding, testing, or writing a new application from scratch. The .NET framework (base class library, presentation foundation, Silverlight, etc.) gives developers a large amount of functionality and power.

Code structure and fundamentals

VARIABLES AND KEYWORDS

- Python statements are usually written one per line, with the new line character signifying the end of the statement.
- Python is case significant

- Python variable names are "bare words" - no preceeding sigil characters.
- Python is a reserved word language - you may NOT use a keyword as a variable name

- Variables are automatcally created in Python when you assign a value to them
- Python does NOT assume that a variable already exists if you try to use a value before one has been assigned
- All Python variables are objects - you do not declare a type. The "subtype" or "subclass" is worked out by the context

- Python programs start running at the top of the file that you tell the language to run. No need to declare a "main" or anything

Example:

width = 16
height = 14.7
depth = 20
what = "cardboard box"

volume = width * height * depth
surface = 2 * (width * height + width * depth + height * depth)
edges = 4 * (width + height + depth)
corners = 6

print "Our",what,"is",width,"by",height,"by",depth
print "Volume is",volume
print "Surface ares is",surface
print "Edge length is",edges
print "Corners",corners

And when I run that ...

wizard:y199.d graham$ python fast1
Our cardboard box is 16 by 14.7 by 20
Volume is 4704.0
Surface ares is 1698.4
Edge length is 202.8
Corners 6
wizard:y199.d graham$

Note:

- int, float and string objects depending on the type assigned to them
- coercion, where a type is silently converted to something more generic (int to float)
- Bodmas; multiplication and division before addition and subtraction, unless amended by brackets
- spaces in source are allowed to help the readability (as used in this example)
- spaces in print; print adds a space between each item printed
- new line is automatically added at the end of each print

INTERACTIVE PYTHON

Python can be run interactively from the command line if you want to try thinsg out. Here's an example where I have done this, callng in a module supplied with Python to look at keywords (it will help answer questions you may have as to "what is a keyword?"

wizard:y199.d graham$ python
Python 2.7 (r27:82508, Jul 3 2010, 20:17:05)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import keyword
>>> print keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with',
'yield']
>>> exit()
wizard:y199.d graham$

COMMENTS, INPUTS AND STRINGS

- comments may be written with a # up to the end of the line
- use ; to put multiple statements on a single source line
- , on end of print will replace the new line character with a space

- input reads from the keyboard and passed the input THROUGH THE PYTHON INTERPRETTER
- raw_input reads from the keyboard and returns a string
- both input and raw_input let you specify a prompt string
- you can get an integer or float out of a string using an int or float function

- strings can be written between single or double quotes - it makes no difference
- If you use triple quotes (either type) you can define a multiline string
- \ sequences are applied in strings - e.g. \n for new line and \" for a "
- the letter "r" in front of a string makes it a raw string
- the letter "u" in front of a string makes it a unicode string

Sample program:

# Fast start example 2 - inputs and strings

# Teaching example

# contrasting input and raw_input
# contrasting single and double quotes
weight = input('How heavy are you [kgs] ')
height = float(raw_input("How tall are you [m] "))
# Need to add - data validation!

bmi = weight / (height * height)

print """This program has asked the user to enter his / her
weight and height and has calculated a body-mass index which
gives a very rough "guestimate" of their potential health.
< 20\tunderweight
20-25\tbest range
25-30\ta bit chubby
> 30\toverweight
But - PLEASE - check with a medical expert too!\n"""

print "Height:",height ; print "Weight:",weight
print "BMI:", bmi

Sample output:

wizard:y199.d graham$ python fast2
How heavy are you [kgs] 79
How tall are you [m] 1.75
This program has asked the user to enter his / her
weight and height and has calculated a body-mass index which
gives a very rough "guestimate" of their potential health.
< 20 underweight
20-25 best range
25-30 a bit chubby
> 30 overweight
But - PLEASE - check with a medical expert too!

Height: 1.75
Weight: 79
BMI: 25.7959183673
wizard:y199.d graham$

Conditionals and loops

CONDITIONALS

All programming languages have the ability to have code which conditionally runs, and code which is repeated. In python:

- Conditional code uses the if keyword
- that is followed by an expression which gives a true or false result
- the condition is terminated by a :
- the code that runs condtionally is EITHER on the same line as the condition OR as an inset block
- the end of an inset block indicates the end of the conditional code
- you may write conditionals within conditionals with a further inset
- inset must be consistent within a block and we ADVISE consistency throughout a program

- comparator operators are < <= > >= == and != (<> is the same as !=)
- comparator operators adapt themselves to work on whatever type of data you compare
- comparisons can be joined with and, or and not keywords

- you can add as many "elif" - else if-s - as you wish onto an if statement
- you can add a single else (a default / catchall) onto an if statement

Sample program:

age = int(raw_input("How old are you in years? "))

if age < 21: print "You are still young"

if age == 54:
    print "You can soon join Melksham 55+"
    print "But they meet during the day on a weekday"
    print "Which isnt great if you're still working"

if age > 16:
    print "You may have completed your education"
elif age < 2:
    print "You are too young to be running this program"
elif age < 5:
    print "You may not have started your education"
else:
    print "You are in fulltime education"
    if age < 12:
        print "at primary school"
    else:
        print "at secondary school"

Sample output:

wizard:y199.d graham$ python if1
How old are you in years? 52
You may have completed your education
wizard:y199.d graham$ python if1
How old are you in years? 54
You can soon join Melksham 55+
But they meet during the day on a weekday
Which isnt great if you're still working
You may have completed your education
wizard:y199.d graham$ python if1
How old are you in years? 56
You may have completed your education
wizard:y199.d graham$ python if1
How old are you in years? 1
You are still young
You are too young to be running this program
wizard:y199.d graham$ python if1
How old are you in years? 4
You are still young
You may not have started your education
wizard:y199.d graham$ python if1
How old are you in years? 6
You are still young
You are in fulltime education
at primary school
wizard:y199.d graham$ python if1
How old are you in years? 12
You are still young
You are in fulltime education
at secondary school
wizard:y199.d graham$

LOOPS

- Python supports 2 loops using the while and for keywords

- a while loop tests a conditition each time around a loop and repeats the code if the condition is still true
- a while loop uses an inset just like the if statement
- a while loop may also have an else clause which is run once the condition has been found to be false
- you may jump out of a while loop using a break statement
- you may jump back to retest the condition at the top of a while loop using the continue statement

Sample program:

purse = float(raw_input("How much money do you have? "))
eachcosts = float(raw_input("How much to they cost each? "))
wanted = int(raw_input("How many do you want? "))

number = 1

while number <= wanted:
    cost = number * eachcosts
    print "If you buy",number,"it will cost",cost
    change = purse - cost
    if change < 0:
        print "You cannot afford this, though"
        break
    print "And you will still have",change,"left"
    number = number + 1
else:
    print "You are able to afford the full number you want"


Sample outputs:

wizard:y199.d graham$ python while1
How much money do you have? 5.00
How much to they cost each? 1.57
How many do you want? 10
If you buy 1 it will cost 1.57
And you will still have 3.43 left
If you buy 2 it will cost 3.14
And you will still have 1.86 left
If you buy 3 it will cost 4.71
And you will still have 0.29 left
If you buy 4 it will cost 6.28
You cannot afford this, though
wizard:y199.d graham$

and

wizard:y199.d graham$ python while1
How much money do you have? 5.00
How much to they cost each? 0.53
How many do you want? 4
If you buy 1 it will cost 0.53
And you will still have 4.47 left
If you buy 2 it will cost 1.06
And you will still have 3.94 left
If you buy 3 it will cost 1.59
And you will still have 3.41 left
If you buy 4 it will cost 2.12
And you will still have 2.88 left
You are able to afford the full number you want
wizard:y199.d graham$

- the for loop goes through a tuple / list / sequence / iteration of values
- each value is turn is placed into a variable for processing
- tuples, lists, sequences and iterations are covered in later modules
- the for loop is NOT a start, step, end loop as it is in most other languages!!

Here is some sample code, stepping through a list, a series of numbers, and even the lines in a data file.

# for loop - iterates through a set

for lang in ("C","C++","Lua","Tcl","Perl","Python","PHP","Ruby"):
    print lang,"is a great programming language"

print "\nSeating people at tables of 4 ..."
for fours in range(11):
    if fours % 4 != 0:
        print fours, "seated. We have some odd seats left"
    else:
        print fours, "seated. Tables filled"

print "\nScanning a data file ..."
count = 0
for lyne in open("requests.xyz"):
    count = count + 1
    if lyne.find("Python") > 0:
        print "line no.",count,": ",lyne,


Sample output:

wizard:y199.d graham$ python for1
C is a great programming language
C++ is a great programming language
Lua is a great programming language
Tcl is a great programming language
Perl is a great programming language
Python is a great programming language
PHP is a great programming language
Ruby is a great programming language

Seating people at tables of 4 ...
0 seated. Tables filled
1 seated. We have some odd seats left
2 seated. We have some odd seats left
3 seated. We have some odd seats left
4 seated. Tables filled
5 seated. We have some odd seats left
6 seated. We have some odd seats left
7 seated. We have some odd seats left
8 seated. Tables filled
9 seated. We have some odd seats left
10 seated. We have some odd seats left

Scanning a data file ...
line no. 8 : hazel PHP Python Perl Ruby ASP
line no. 12 : leane PHP Python ASP Perl Java
line no. 15 : olivia MySQL Python ASP PHP
line no. 27 : adam Tcl/Tk Perl Python MySQL
line no. 28 : barry Python XML Java Perl PHP
line no. 34 : harry PHP Python Java
line no. 37 : ken Tcl/Tk Python Java Perl
line no. 40 : nigel PHP Python Java Perl
line no. 44 : rupert Java Python MySQL
wizard:y199.d graham$

Exercise




See also Python Programming course

Please note that articles in this section of our web site were current and correct to the best of our ability when published, but by the nature of our business may go out of date quite quickly. The quoting of a price, contract term or any other information in this area of our website is NOT an offer to supply now on those terms - please check back via our main web site

Related Material

Python - Fast Start
  [4713] Equality (in Python) - (2016-10-30)
  [4712] A reminder of the key issues to consider in moving from Python 2 to Python 3 - (2016-10-30)
  [4709] Some gems from Intermediate Python - (2016-10-30)
  [4707] Some gems from an introduction to Python - (2016-10-29)
  [3519] Python - current versions and implementations (CPython, Jython, IronPython etc) - (2011-11-13)
  [2017] Python - a truly dynamic language - (2009-01-30)

Python - General
  [4712] A reminder of the key issues to consider in moving from Python 2 to Python 3 - (2016-10-30)
  [4656] Identifying the first and last records in a sequence - (2016-02-26)
  [4558] Well House Consultants - Python courses / what's special. - (2015-10-28)
  [4434] Public training courses - upcoming dates - (2015-02-21)
  [4408] Additional Python courses added to our schedule - (2015-01-29)
  [4295] A longer Python ... training course - (2014-09-16)
  [4236] Using Python to analyse last years forum logs. Good coding practise discussion. - (2014-01-01)
  [3935] Whether you have programmed before or not, we can teach you Python - (2012-11-25)
  [3911] How well do you know Perl and / or Python? - (2012-11-04)
  [3903] Python Programming class for delegates who have already self-taught the basics - (2012-10-25)
  [3902] Shell - Grep - Sed - Awk - Perl - Python - which to use when? - (2012-10-22)
  [3816] Want to escape the Olympics? Learn to program in the countryside! - (2012-07-23)
  [3798] When you should use Object Orientation even in a short program - Python example - (2012-07-06)
  [3519] Python - current versions and implementations (CPython, Jython, IronPython etc) - (2011-11-13)
  [3489] Python courses and Private courses - gently updating our product to keep it ahead of the game - (2011-10-20)
  [3463] Busy weekend of contrasts. - (2011-10-03)
  [3076] Python through the Snow - (2010-12-01)
  [2822] Python training courses for use with ESRI ArcMap software - (2010-06-23)
  [2778] Learning to program in Python 2 ... and / or in Python 3 - (2010-05-24)
  [2504] Learning to program in ... - (2009-11-15)
  [2394] Two days of demonstration scripts in Python - (2009-09-05)
  [2367] Learning to program - how to jump the first hurdles - (2009-08-20)
  [2285] Great new diagrams for our notes ... Python releases - (2009-07-13)
  [2227] Learning PHP, Ruby, Lua and Python - upcoming courses - (2009-06-11)
  [2020] Learning Python - many new example programs - (2009-01-31)
  [2017] Python - a truly dynamic language - (2009-01-30)
  [16] Python training - (2004-08-16)

Introduction to Python
  [4590] Progress on moving from Python 2 to Python 3 - training for both versions - (2015-12-01)
  [4298] Python - an interesting application - (2014-09-18)
  [4118] We not only teach PHP and Python - we teach good PHP and Python Practice! - (2013-06-18)
  [1663] Python in an afternoon - a lecture for experienced programmers - (2008-06-01)
  [1375] Python v Ruby - (2007-10-02)
  [950] Python and the Magic Roundabout - (2006-11-27)
  [949] Sludge off the mountain, and Python and PHP - (2006-11-27)
  [909] Python is like a narrowboat - (2006-10-30)
  [846] Is Perl being replaced by PHP and Python? - (2006-08-27)
  [834] Python makes University Challenge - (2006-08-15)
  [753] Python 3000 - the next generation - (2006-06-09)
  [745] Python modules. The distribution, The Cheese Shop and the Vaults of Parnassus. - (2006-06-05)
  [712] Why reinvent the wheel - (2006-05-06)
  [710] Linux training Glasgow, Python programming course Dundee - (2006-05-05)
  [629] Choosing the right language - (2006-03-01)
  [444] Database or Progamming - which to learn first? - (2005-09-13)
  [382] Central London Courses - Perl, PHP, Python, Tcl, MySQL - (2005-07-18)
  [380] Bridging to the customer requirement - (2005-07-16)
  [317] Programming languages - a comparison - (2005-05-20)

Python - Fundamentals
  [4712] A reminder of the key issues to consider in moving from Python 2 to Python 3 - (2016-10-30)
  [4442] Mutable v Immuatble objects in Python, and the implication - (2015-02-24)
  [4324] Learning to program - variables and constants - (2014-11-22)
  [3917] BODMAS - the order a computer evaluates arithmetic expressions - (2012-11-09)
  [3886] Formatting output - why we need to, and first Python example - (2012-10-09)
  [3551] Some terms used in programming (Biased towards Python) - (2011-12-12)
  [3278] Do I need to initialise variables - programming in C, C++, Perl, PHP, Python, Ruby or Java. - (2011-05-05)
  [3181] Beware - a=a+b and a+=b are different - Python - (2011-02-23)
  [3083] Python - fresh examples from recent courses - (2010-12-11)
  [2778] Learning to program in Python 2 ... and / or in Python 3 - (2010-05-24)
  [2442] Variable storage - Perl, Tcl and Python compared - (2009-10-08)
  [2368] Python - fresh examples of all the fundamentals - (2009-08-20)
  [1878] Pascals Triangle in Python and Java - (2008-11-10)
  [1461] Python - input v raw input - (2007-12-06)
  [1448] Question on division (Java) - Also Perl, PHP, Python ... - (2007-11-28)
  [1430] Integer v float - Python - (2007-11-12)
  [956] Python security - trouble with input - (2006-11-30)
  [748] Getting rid of variables after you have finished with them - (2006-06-06)
  [633] Copying a reference, or cloning - (2006-03-05)
  [328] Making programs easy for any user to start - (2005-05-29)

resource index - Python
Solutions centre home page

You'll find shorter technical items at The Horse's Mouth and delegate's questions answered at the Opentalk forum.

At Well House Consultants, we provide training courses on subjects such as Ruby, Lua, Perl, Python, Linux, C, C++, Tcl/Tk, Tomcat, PHP and MySQL. We're asked (and answer) many questions, and answers to those which are of general interest are published in this area of our site.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2019: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01225 708225 • FAX: 01225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/solutions/python-p ... start.html • PAGE BUILT: Wed Mar 28 07:47:11 2012 • BUILD SYSTEM: wizard