Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
 
For 2023 (and 2024 ...) - we are now fully retired from IT training.
We have made many, many friends over 25 years of teaching about Python, Tcl, Perl, PHP, Lua, Java, C and C++ - and MySQL, Linux and Solaris/SunOS too. Our training notes are now very much out of date, but due to upward compatability most of our examples remain operational and even relevant ad you are welcome to make us if them "as seen" and at your own risk.

Lisa and I (Graham) now live in what was our training centre in Melksham - happy to meet with former delegates here - but do check ahead before coming round. We are far from inactive - rather, enjoying the times that we are retired but still healthy enough in mind and body to be active!

I am also active in many other area and still look after a lot of web sites - you can find an index ((here))
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
  [2017] - ()
  [3519] - ()
  [4707] - ()
  [4709] - ()
  [4712] - ()
  [4713] - ()

Python - General
  [16] - ()
  [2017] - ()
  [2020] - ()
  [2227] - ()
  [2285] - ()
  [2367] - ()
  [2394] - ()
  [2504] - ()
  [2778] - ()
  [2822] - ()
  [3076] - ()
  [3463] - ()
  [3489] - ()
  [3519] - ()
  [3798] - ()
  [3816] - ()
  [3902] - ()
  [3903] - ()
  [3911] - ()
  [3935] - ()
  [4236] - ()
  [4295] - ()
  [4408] - ()
  [4434] - ()
  [4558] - ()
  [4656] - ()
  [4712] - ()

Introduction to Python
  [317] - ()
  [380] - ()
  [382] - ()
  [444] - ()
  [629] - ()
  [710] - ()
  [712] - ()
  [745] - ()
  [753] - ()
  [834] - ()
  [846] - ()
  [909] - ()
  [949] - ()
  [950] - ()
  [1375] - ()
  [1663] - ()
  [4118] - ()
  [4298] - ()
  [4590] - ()

Python - Fundamentals
  [328] - ()
  [633] - ()
  [748] - ()
  [956] - ()
  [1430] - ()
  [1448] - ()
  [1461] - ()
  [1878] - ()
  [2368] - ()
  [2442] - ()
  [2778] - ()
  [3083] - ()
  [3181] - ()
  [3278] - ()
  [3551] - ()
  [3886] - ()
  [3917] - ()
  [4324] - ()
  [4442] - ()
  [4712] - ()

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., 2024: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 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