Featured

Linux in a nutshell

Get picture here

Contents:

  1. Introduction
  2. What is “Linux”?
  3. Design
  4. Why Linux?
  5. Linux Distributions
  6. Install

Introduction

Before we get into answering the big question, I’d like to point out that this is merely a short introduction for beginners to wrap their minds around what “Linux” basically is. This article was explicitly tailored for people who are new to Computer Science in general, therefore the contents you’ll be finding below will only unpuzzle the utmost fundamentals of Linux as well as give out essential guides for our curious novices to get started with using this amazing, as you’ll find out very soon, Operating System.

What is “Linux”?

Have you ever wondered how strings of zeros (0) and ones (1) are capable of interacting with the physical hardware of machines? From the computer at your office to the smartphone you’re supposedly using to read this article with, these technological wonders all share one thing in common: they have an Operating System.

<NULL>

Design

PYTHON PROGRAMMING (2/9)

March 24, 2019

WELCOME TO PYTHON 3

METROPOLIA UAS

Get picture here

 

Table of Contents

Chapter 2: Fundamentals of the Python language

2.1 Comments and variables

  • Comments in source code

Inline commenting

  • Example 2-1: Comments in the source code

Variables

  • Making a variable
  • Using variables with a command
  • Example 2-2: Creating and using variables

Variable naming conventions

2.2 Different printing techniques

  • THE PRINT COMMAND

 

Chapter 2: Fundamentals of the Python language

In this chapter we will discuss the fundamental concepts of the Python language, such as naming conventions of variables, different types of comments and such. This chapter is rather long, but the things introduced here will be used throughout the course, and the only way to be able to meaningfully discuss the more advanced structures is by understanding the basics. Obviously, there are some things which may not be immediately relevant, but it is OK to return to this chapter now and then to remind oneself on how, for example, string slicing is done.

 

2.1 Comments and variables

 

In this chapter, the aim is to teach the basic things about Python syntax before advancing to the more complex structures. Rather funnily, the first thing discussed has nothing to do with actual programming, at least in theory. That is commenting and comments in general.

The topics covered in this chapter from here onward are also discussed in the book chapter 2.

In some cases it is important to be able to write random notes and reminders in the code to describe how the program should work, or why some part of the program is implemented as it is. This is especially important when the program size starts to grow beyond 150 lines of code limit and it becomes impossible to remember all the details at once, or there are other people contributing to the software. Comments are an important way of understanding how things are supposed to work.

Comments in source code

Commenting in programming means the task of writing instructions and notifiers in the source code to remind oneself and possible other programmers of the details in the code. In general, comment lines are meant for other humans, so they are open, informal, freely typed text, which is intended to merely convey knowledge. For this same reason, comments do not affect the way the source code is executed. Normally the interpreter simply bypasses the lines which start with the comment sign.

In Python a line is marked as a comment by starting it with the # character (Shift-3). If this character is the first character on a line, it means the interpreter simply skips forward to the begining of the next source code line. For example, the line

# This here is simply comment, the code to come does stuff

would be completely bypassed. Even in a case where the comment line has source code such as this

# pritn("This here should be printed."

the line is bypassed without any error, even though the line is obviously code, has a typo in the print command and is missing the closing parenthesis “)”. This is because the line is marked as a comment. In fact, this is one of the applications for comments; taking out source code which is no longer needed but still too valuable to completely erase. It can simply be bypassed by “commenting it out”.

 

Inline commenting

 

Besides separate comments, the comment can be placed after a working line. For example, the command

print("This is important!") #Comment!

actually has both a command and a comment on the same line. The interpreter first reads the command normally, and then skips to the next line when the comment character ‘#’ is encountered. This way of adding a comment to the end of a normal command line is called inline commenting, and can be used to emphasize a single command or denote a part which really needs attention. However, when using inline comments the actual command on the line has to be functional; for the interpreter the line with the inline comment is the same as any other normal line of code.

In Python there is one exception to the rule “comments do not affect how a program is executed”: the first line and code page declaration. In fact, this exception has been used in the examples of the last chapter! The very first line of code in the source code file tells the interpreter what character sheet (code page) the source code was written with, affecting the way the interpreter works with the non-English letters such as A-umlaut (Ä) or o-umlaut (Ö), which are popular in the Nordic languages.

Example 2-1: Commments in the source code

Source code

# -*- coding: cp1252 -*-
  
print("This line will be printed.")
#This is a comment, interpreter cannot see me!

print("This is the second printed line.")
#print("This print command is commented away.")
  
#The next line has an inline comment:
print("This is the third printed line.") #Comment!

# This comment is divided
# into several lines of code. The interpreter does not
# care about this as long as every line starts with "#".
 
print("This is the last printed line.")

Output

>>> 
This line will be printed.
This is the second printed line.
This is the third printed line.
This is the last printed line.
>>>

The most important thing to remember is that the lines starting with the # character are not source code, but instructions for the programmer. In the latter examples in this course, comments are only used to describe what the code is doing, they do not affect the way the program works in any way.

 

Variables

 

Another fundamental concept in programming is variables. Variables can be considered as a container or “a box”, which can be used to save data such as a name or value for later use. Making a variable is easy: first the variable is given a name, and then an initial value with operator “=”. Unlike some other programming languages, in Python the variable does not have to be introduced separately, nor is it bound to a certain type of data. When the variable is created, the content type can be changed whenever and to whatever during program execution. In the following example this is demonstrated:

>>> value = 100
>>> print(value)
100
>>> value = "FluffyTheTerrible"
>>> print(value)
FluffyTheTerrible
>>> 

As demonstrated by the code, the given value is saved to the variable, which can be then used as a substitute for the actual written value in command. The contents of the variable can also be rewritten by simply assigning the new value.

Making a variable

A variable can be made in any part of the source code, unlike in programming languages such as C, where every variable has to be introduced at the beginning of the code. Obviously in some cases the variable has to exist before it is used, such as in using it as a selection variable, because the interpreter cannot just guess a value for them and therefore cannot know if the variable is more or less than five, or true or false, if it does not know the variable beforehand.

>>> stringline = "Teapot"
>>> number = 1100
>>> print(stringline)
Teapot
>>> print(number)
1100
>>> 

In this code, two variables named stringline and number are made. A character string “Teapot” is saved into the variable stringline, and number gets the value 1100 as an initial value. Make notice of the citation marks, they are used to denote a string in the Python, as strings can have whitespace characters (line breaks, spaces and tabulations) without any restrictions. With numbers the citation marks are not needed: the interpreter understands that a group of numbers denote one value. This is discussed in more detail later.

Using variables with a command

The printing command print reacts to variables as it would to normal text. The interpreter sends the contents of the variable to the print command, meaning that print actually gets the contents, not the name of the variable to work with. This is also the reason why variables work in programming, they are more or less “placeholders” for values, and the interpreter takes care of seeing that the values the variables represent are used and saved correctly. This also is the reason why variables can substitute, and even be compared to solid, static values!

>>> variable = "Coffeemug"
>>> print(variable)
Coffeemug
>>> stuff = variable
>>> print(stuff)
Coffeemug
>>> number + 150
1250
>>> 

Besides substituting static values, the variables can be used for example in calculations. In the last example, the variable value is assigned to another variable, and the variable value is modified by adding another number. However, when doing this there is a possibility for a problem: if the command is

>>> name + 500

this causes an error message

Traceback (most recent call last):
File "", line 1, in 
name + 500
TypeError: Can't convert 'int' object to str implicitly
>>> 

because the interpreter cannot add numbers to a string and thus this causes a type error, which then ends the program. This is discussed more later.

Example 2-2: Creating and using variables

Source code

# -*- coding: cp1252 -*-

message = "I am the harbinger of doom."
print(message)

print(message)
print(numbervalue)

word = "blueberries."
print("I would like to have ice cream and",word)

Output

>>> 
I am the harbinger of doom.
42
I would like to have ice cream and blueberries.
>>>

 

Variable naming conventions

 

There are some restrictions on the names that can be given to a variable. The first rule is that the name cannot be anything from the list below, as these names are reserved for the program language syntax. The syntax is the vocabulary of the programming language, and the syntax words define the programming structures so, as to avoid confusion, these names are made unavailable.

and elifimportreturn
aselseintry
assertexcept iswhile
breakfinallylambdawith
classfornotyield
continuefromor
defglobalpass
delifraise

Table 2.1 Reserved names in the Python language

Otherwise the name has to be composed of normal, lower or uppercase letters of the English dictionary (a,b,c…,z, A,B,C…,Z) or numbers (0…9). In addition, underscore ( _ ) can be used to separate different parts of the name, as the variable name cannot have whitespace characters such as space (‘ ‘). Other characters, such as dollar signs ($) or percents (%) or non-English letters (Å, Ä, Æ, Ü …) cannot be used, and the first character cannot be a number, even if they are otherwise allowed. The table 2.2 has some examples of variable names.

Variable name Will it work?
flag Yes it will, it fulfills all of the requirements.
conTROl
Yes it will, there are no technical restrictions on mixing lower and uppercase characters.
setting_2 Yes it will, numbers are allowed as long as they are not the first character, as is the underscore.
_sign Yes it will, underscore can be the first character.
10th_item No it won’t, the name cannot begin with number.
two-parter No it won’t, the normal dash is not allowed.
%checksum No it won’t, there is non-allowed character (%).
hääyöaie No it won’t, the letters should be from English vocabulary.

Table 2.2 Examples of Python naming convention

Something to take note of are the names which start with two underscores (like __doc__). These variables are internal, automatically generated names which are usually related to objects and classes. These variables are usually meant only for the internal use, and should not be edited manually. Unless there is a real need to do so, these variables should be left alone.

 

2.2 Different printing techniques

 

THE PRINT COMMAND

So far we have been using the print command to print out stuff, but have not discussed the actual application methods of this command. The way we have been working so far has been the normal

<NULL>

PYTHON PROGRAMMING (1/9)

March 19, 2019

WELCOME TO PYTHON 3

METROPOLIA UAS

Get picture here

 

Table of Contents

Chapter 1: Regarding the course

1.1 The main differences between python 2 and Python 3

Printing

Inputs

1.2 Python and other programming languages

APPLICATIONS OF DIFFERENT LANGUAGES

DIFFERENT PROGRAMMING STYLES

Python compared to other languages

Application areas for Python

1.3 Using the Python interpreter

INSTALLING PYTHON ON THE WORKSTATION

Additional module libraries

Python Imaging Library

Python Cryptography toolkit

Numeric Python

PyGame

Python Win32 Extensions

Py2Exe

Django

REGARDING THIRD PARTY MODULES IN GENERAL

THE MODULE LIBRARY OF THE STANDARD INSTALLATION

1.4 Getting to know the interpreter

1.5 The first Python program

Example 1-1: The first Python program

 

Chapter 1: Regarding the course

Welcome to the introduction to Python-programming! During this course, we will take a look into the fundamentals of Python 3 programming, covering the basic components and structures of the Python language. The level of this course is low enough for those who wish to learn Python as their first language, but is mainly intended for people who, prior to this course, have studied programming with some other language, or at least understand the very basic ideas of programming. This course also works as a supplemental course for those who already know version 2 of Python and would like to test the differences of the new version. The course material focuses on introducing the concepts of Python 3, and by presenting code examples, easing the process of understanding how Python works.

Hopefully you’ll enjoy the course!

This course also supplements and supports the usage of the WSOYPro/Docendo book Python 3 —ohjelmointi (currently only available in Finnish). These information boxes offer direct references to the book, indicating the chapter which contains information that the course is currently discussing.

For those who have already read the book, this course mostly offers exercises and additional information to find all the best sources regarding the Python programming. In addition to the exercises and links to further reading, some of the topics are presented in more detail than in the book.

 

1.1 The main differences between Python 2 and Python 3

 

Python 3 is the newest major version of the Python programming language. Python 3 was released December 2008, and the newest subversion, 3.1.3, was launched 27th November 2010. The largest differences between the second and third versions is that Python 3 streamlines the language syntax and improves some functionalities such as input handling. The changes have unfortunately made Python 3 backwards incompatible with earlier versions of Python. Breaking backwards compatibility has however paid off in several ways. For example, the syntax has been cleaned of almost all special cases such as the print command, which now operates as a function. Similarly, the old datatype-specific input function has been eliminated, and replaced with raw_input. The main differences can be summarized as follows:

  • The print command functions like a proper function, and accepts additional arguments to define the end-line and division characters.
  • Comparison between two different sequences (for example list and tuple) with logical operators raises TypeError, instead of returning a Boolean character defined with arbitrary and confusing comparison rules, which was the case in Python 2. In Python 3 if the operands do not have a meaningful natural ordering, they cannot be compared against each other besides with == and != operators.
  • String formatting with the % operator is deprecated starting with version 3.1. There is a new method for string formatting, operating as a format method for string datatypes.
  • Input handling is solely done via a function called input, which operates exactly as the raw_input in Python 2. There is no separate raw_input in Python 3.
  • Division operator (/) returns float, even with two interger values, if the result has non-zero decimals. The old division operator can be used with syntax “//”, like results = 10//3.

The following code examples illustrate the main differences:

 

Printing

 

Python 2 print command:

print “Welcome to the course!”,

The same code in Python 3:

print(“Welcome to the course!”,end = “”)

The difference is that the Python 3 print is a proper function, unlike the earlier print-operator which applied its own rules and designs. Because print is now a function, it also has two arguments, end and sep, which make it easier to achieve some of the layout tricks used with the previous printing command.

Inputs

In Python 2, the input is taken as follows:

value = input(“Please insert value: “)

or alternatively

value = int(raw_input(“Please insert value: “))

The same command with Python 3:

value = int(input(“Please insert value: “))

The old type-specific input has been eliminated and the new function operates similarly to the old raw_input.

The full list of changes made to Python 3 (compared to Python 2.6) is available online at http://docs.python.org/py3k/whatsnew/3.0.html

 

1.2 Python and other programming languages

 

Deep down in the system, computers process every piece of information as a stream of ones and zeros, which dictate whether the computer reads or writes memory banks, calculates things, sends messages forward to the auxiliary systems or does something else. This steam of ones and zeroes is called machine code, which in principle is a programming language composed of primitive commands and instructions used by the computer system itself. As machine code is really a cumbersome, error-prone and primitive way to express actions, it is not really used directly in programming tasks by anyone except maybe the very top level gurus of programming. These limitations lays the reason for programming languages to exist: to help people tell computers what to do, by providing a means to express oneself easily, but in a manner which the computer system also understands.

APPLICATIONS OF DIFFERENT LANGUAGES

However it was soon discovered that one language cannot be specific yet dynamic enough to cater for all the different uses for computers, so the development of programming languages started to head towards specialized languages. For example PHP, Java, Python and C++ are rather well-known programming languages, which all have different strenghts and weaknesses in terms of applicability. PHP is really well-suited for creating web services, whilst Java is excellent for building platform-independent software, and C++ can beat almost any language in pure performance and code optimisation. Basically the selection of the language is akin to using the right tool for the job: creating a C++ -based browser application or an embedded Java program for a hardware system is really difficult, or at least laborous, because the languages aren’t intended to be used for those sorts of purposes.

Besides the application domain, another way to differentiate between the different languages is the division between high-level and low-level languages, based on how much abstraction is available between machine code and the programming language. In the low level languages such as C, commands and available actions differ only little from the pure machine code presentation. The programmer has to implement features such as memory management and dynamic structures by hand, and only little automation is usually available for tasks such as using an Internet connection or using a graphical interface. The upside to this is that the code can be made really efficient and quick, and the programmer knows every detail of how the program operates. In high-level programming languages such as Python, the details are left to the interpreter or compiler to worry about, while the programming tasks focus on more high-level activities, such as defining how the GUI should look, or what kind of data is searched from the database.

DIFFERENT PROGRAMMING STYLES

Besides high and low level programming the different programming languages also support different programming styles, which are also called paradigms. Programming paradigms mean the fundamental ways how the source code is structured: in procedural programming, the source code is made of functions and variables, whereas in object-orientation the code is mostly objects and methods. In procedural programming the program operates so that there are functions which perform actions, and arguments or variables, which exchange knowledge between the functions. In object-orientation, activities are made inside self-contained classes, from which a group of objects is created to perform different tasks. In any case, there are different programming paradigms which define how the code is structured; in mathematics, there is the functional paradigm which focuses on defining what is modified instead of how it is modified, and with advanced interfaces, it is common to create event-driven code, where activities are defined as a response to the different things the user can do, like pressing a button or pushing a switch.

However, unlike the division between high and low-level programming languages, one programming language is not only tied to one programming paradigm. For example, Python, the programming language used in this course, can be used with procedural, object-oriented, and event-driven paradigms. By expanding the command library, it can be argued that even functional programming becomes possible. This is possible because of a high level of abstraction; because Python is a high-level language, the syntax and logic behind the language is not that restrictive and the source code can be made to work in several ways. In low level languages, the restrictions usually cause the language to select one programming paradigm, but implement it very well.

 

Python compared to other languages

 

In a way, Python is a peculiar language, as there really is no clear niche the language is aimed at. Based on application areas where the language is mostly used, it is close to Perl, although with much clearer syntax and better support for platform independence. However, when building stand-alone software, it can work as well as C++ or Java, and in network services, it can be supplemented with the right extensions to be comparable to Ruby on Rails, or even PHP.

Originally the Python language was created as an extension for a language called ABC, with features taken from languages such as Modula-3, Haskell, Lisp and Perl. In later development, there are distinct similarities with C and Java. The original implementation of Python interpreter, CPython, was programmed with the C language. The main features of Python can be summarized as follows:

  • Instead of brackets { and }, Python uses indentation as the divider for logical source code blocks.
  • Variables are dynamically typed, so their contents can be redefined without any restrictions; a string can be given as a value to a variable which previously had an integer. There also is no need to separately declare the variables, they can be created “on-the-fly” when needed within the source code.
  • The syntax is primarily designed to be understandable, simple and minimalistic. This is the reason why one of the most common application areas for Python is as the first taught language in introductory programming courses.
  • Even though Python is originally an object-oriented language, the syntax is designed to allow procedural programming and ignore the object-oriented stuff such as class declarations. In addition, with additional libraries the language can be extended to allow several other programming paradigms.
  • Python is delievered with “everything including the kitchen sink”: The standard installation package comes with an extensive module library and all of the needed software to get started. There is no need for separate function libraries, editor packages or other things to try and start with the language.
  • There are several strong suites within the Python core functionalities: extensive structured data types, several data manipulation methods and especially strong string operators.

On several occasions, the Python has been said to combine the straightforwardness of scripts with the possibilities of programming languages. However, it should be noted that Python is not a scripting language, but rather a high-level programming language which can, and is, used to create commercial, complete software. The main design principles of the Python langauge have also been expressed as a poem:

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one — and preferably only one — obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!

This poem is usually called the Python Zen which lays the foundation for further development of the language. This, and many other design principles and comments on existing features can be found at the Python Enhancement Proposals, which are publicly available at http://www.python.org/dev/peps/.

 

Application areas for Python

 

Even though it is true that Python can be used to create complete programs, it is a rather unusual application area for Python. In professional development, Python is usually applied as a support language to create small tool functionalities such as data generators or filters. In addition to tool funtions, Python is also used to make small programs such as hex calculators, IRC-bots or image converters. For this area of application, Python has a module for creating a graphical user interface with a small amount of code:

from tkinter import *
import sys
def endme(): window.destroy() sys.exit(0)
window = Tk()
text_window = Label(window, text = "Tkinter in action") text_window.pack()
endme_button = Button(window, text = "Quit", command = endme) endme_button.pack(side = BOTTOM)

window.mainloop()    

This small snippet of source code defines a program, which has a window, a text box with a short description, and a button that has functionality to end the program. Also, because Python is a platform independent programming language, this program works in all of the different operating systems (for example Windows Vista/7, OSX, Linux distributions…) for which the Python interpreter and the standard module library is implemented.

Besides easy GUI generation, the ability to modify strings has been a large marketing point; the ability to edit and slice character strings and dynamic structures is exceptionally well implemented and easy to use. For example, one fairly common exercise in string comparisons is the palindrome test. In Python, the actions required to turn the string backwards and compare it against the original makes this exercise almost trivial:

Source code

01  # -*- coding: cp1252 -*-
02
03  while True:
04      word = input("Give the tested string: ")
05
06      #test if the string backwards is same as the original
07      if word == word[::-1]:
08          print("Given string,",word,"is a palindrome!")
09      else:
10          print("String is not a palindrome.")
11          
12
13      decision = input("Test another? (Y/N): ")
14  
15      if decision == ("N" or "n"):
16          print("Program has been terminated.")
17          break

Result

>>> 
Give the tested string: oolated squigg
String is not a palindrome.
Test another? (Y/N): y
Give the tested string: racecar
Given string racecar is a palindrome!
Test another? (Y/N): n
Program has been terminated.
>>> 

Notice, that the actual conversion and comparison for the string is implemented as one command on line 7. Everything else in the code is “fluff” used to define and build the program interface.

 

1.3 Using the Python interpreter

 

The development and distribution of the Python interpreter is done by the non-profit organisation called the Python Software Foundation (http://www.python.org), from which the installer package for the interpreter and all of the basic tools are available. This installation package includes all of the essential tools for basic programming: an interpreter, debugging tools for finding errors from the software and, most importantly, a source code editor called IDLE. In addition, all of the included tools are platform-independent, meaning that by learning the ropes of the tools allows programming in all of the most usual PC operating systems (Windows XP/Vista/7, Linuxes, MacOS…). This is also the reason why this course expects you to use these tools: they work regardless of the actual system you are using. However, if you are using this course with other tools, for example a different editor, it is still wise to use the actual PSF-version of the Python interpreter.

Additionally, if the source code editor you are using is not IDLE (or the Viope editor window), it is wise to make sure that the editor actually understands how Python syntax works. The Python language has eliminated brackets ( “(“, “)”, “{}” etc.) from the syntax almost completely, but uses indentation to denote the logical groupings of the code. This is discussed in more detail later, but for now remember two things: A) if in doubt, use IDLE or the Viope editor and B) do not indent the source code unless especially told to do so.

INSTALLING PYTHON ON THE WORKSTATION

These instructions are meant for permanent installation of the Python interpreter and the basic tools for a workstation. This is completely optional, as everything in this course can be done with the Viope system. If you do not want to, or cannot install Python on your workstation, you may freely skip forward a couple of pages to the last page of this chapter.

The installation of the Python interpreter is rather straightforward and does not need any special skills. The Python interpreter does require administrator rights for guaranteed successful installation, so unless you are doing the installation on your own computer, you will need a person with the sufficient rights to do the installation. There is also the possibility that the installation package has changed after these instructions were written, so use these instructions only as an advice, and do what the installation asks, if the package instructions differ from these.

On Windows workstations, the first action is to grab the installation package from the the Python website. This website is at the address www.python.org, and it does not need any separate registration or user account for fetching the installation packages.

On the left sidebar of the main page is a title “Quick Links (3.2)”, and subtitle “Windows Installer”. By clicking this link, the browser should immediately try to load the installation package named “python-3.2.msi”. Save this file to the download directory. Please notice, that the actual quick link always directs to the newest installation packages of both Python 2 and Python 3. The Python 3 package can be identified with the “3” as the first number of the version. At the moment this instruction was written, the selection was Python 2 with version 2.7.1 and Python 3 with 3.2.

When the package has loaded (it should be approximately 20 megabytes) run the package. In the installation, ensure that all of the package contents are installed, and accept the default settings. This installs Python interpreter on the C-drive, in directory C:\PythonXY, where X and Y denote the actual version number. Boot the system afterwards to finalize the installation.

On most Linux systems the Python can be installed from the package manager, as Python usually is included in the standard package repository. Please ensure that the installed version is “3.-something”, as in many systems Python 2 is still the “default” Python.

On Mac systems the installation packages can be found at the Python homepage http://www.python.org by following a link “Download” at the upper left hand corner of the main page. Select the most appropriate installation package depending on your hardware, and run the installation as an admin.

 

Additional module libraries

 

The design principles of everything plus kitchen sink in Python basically means that the installation package should be enough for most basic needs in programming. This is most obvious when looking at the installation package: it has everything needed to start writing working Python code regardless of the actual platform, with an extensive module library which allows several different special activities such as GUI programming, using the network connection or engineering calculus.

However, the Python is also known for its extensive library of additional modules, which extends the already huge library of premade functions even more. However, it is sad to say that the migration of some of the more useful third party libraries to the Python 3 has been somewhat slow. In any case, below are listed some of the most important additional Python libraries. Several of them currently exist only as Python 2 compatible versions, but this will surely change in the future.

Python Imaging Library

The Python Imaging Library (http://www.pythonware.com/products/pil/) is a group of extra modules which enables Python to create and edit basically any image format available. This module has an extensive selection of different picture manipulation tools and different filters for doing pretty much anything any good picture editing software would be able to do. Currently the Python 3 version is not available, but there is a promise on the module home site that it will be “released later”.

Python Cryptography toolkit

The Python Cryptography toolkit (http://www.amk.ca/python/code/crypto) is a toolset meant for working with different cryptography algortihms and coding schemes. Somewhat hard to find on the Internet, as several countries still restrict the distribution and usage of said functions.

Numeric Python

Numeric Python (http://numpy.scipy.org/) has even more tools for scientific calculations and engineering calculus. Another notable feature is the ability to do matrix calculations, similarly to Matlab. Available for Python 3.2.

PyGame

PyGame (http://www.pygame.org/) is a module library which is intended to help with the creation process of computer games.

Python Win32 Extensions

The Python Win32 Extensions (http://python.net/crew/mhammond/win32/) is a group of extra modules and features which integrates the Python interpreter even more deeply to the Windows system. Not very useful on its own, but a required module for some of the other modules in this page.

Py2Exe

Py2exe (http://www.py2exe.org/) is a module which allows the programmer to compile (or more accurately wrap) Python source code into an executable package which does not need a separate Python interpreter to work on a Windows workstation. A Python 3 version is in development, but the project currently seems a bit deceased.

Django

Django (http://www.djangoproject.com/) is a large module which itself almost deserves a separate entry under programming languages. Django makes Python a language to create and maintain websites —  something that was previously lacking from the Python language itself, but readily available for one of the most important competitors of Python, the Ruby programming language (with the Ruby on Rails framework). A version for Python 3 is currently “in development”.

REGARDING THIRD PARTY MODULES IN GENERAL

When getting these packages, attention should be paid on the version number of the Python interpreter the package is intended for. A package meant for Python 2.5 will not work with Python 3.X, even if in some random cases it happens to install. The third party modules are also not always professionally made. Usually they are a product of a small group of enthusiasts or a non-profit group. They may have errors or problems in execution or compatibility.

THE MODULE LIBRARY OF THE STANDARD INSTALLATION

Besides third party material, the installation package also contains several useful and interesting modules which are there to help with implementing some of the more difficult tasks such as networking. The easiest way of getting to know these modules is to, from the Start menu, select the shortcut Python manuals, or in the interpreter window select, from the drop-down menu, Help->Python Docs (hotkey F1). This documentation contains all the official documentation for the interpreter and modules, and is actually pretty useful, albeit with a limited selection of complete, functional source code examples.

The most recent and updated version of this material is also available online, in the documentation repository at address http://docs.python.org/py3k/

 

1.4 Getting to know the interpreter

 

Now that the interpreter is installed, its time to try to use it for the first programming exercise. The first thing to do is to start the interpreter by navigating to the Python-named folder in the Start menu, and selecting a shortcut named “IDLE (Python GUI)”. When the interpreter starts, it should open the interpreter window, which is a mostly white window with the following text:

Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32

Type “copyright”, “credits” or “license()” for more information.

>>>

The easiest way of testing whether the installation was successful is to write the command import sys in this window. This command imports a library module called sys, which has several system-related functions. If the command is successful, and no error message is given, then the interpreter should have everything in satisfactory condition:

>>> import sys

>>>

Some older spyware detectors and firewalls may sometimes block the interpreter from starting, causing an error “Subprocesses did not connect”. The best way to deal with this error is to give a program executable named “pythonw.exe” in folder C;\PythonXY\ all networking and excecution rights on the local workstation.

Now that the interpreter is running and installed correctly, it’s time to look around a bit. First of all, when the interpreter starts, it opens a new window called “interpreter shell”, and prints the current version number of the installed interpreter. In this window, there is also a command line prompt with preceding characaters “>>>”. At this prompt, different Python commands can be tried out to test how the interpreter would react. In this course, if some code example has the preceding “>>>”, it means that this command is written directly to the interpreter shell. For example, giving the print command causes the interpreter to print the given text:

>>> print(“Test!”)

‘Test!’

>>>

Similarly, the interpreter can also act as a calculator with numbers and the normal mathematical operators (+, -, /, * etc.)

>>> 3 + 5

8

>>> 45 / 6

7.5

>>>

The interpreter shell is useful for testing out stuff, but it is not very good for writing actual programs as the interpreter keeps responding when the ‘Enter’-key is pressed. Real programs are written in a separate file, and they willl most definitely have more than one command. It is also important for execution that the interpreter should not “think out loud”, as it does in the interactive shell. All this can be done by opening a new editing window from the shell window.

To open a new editing window, simply select File->New Window from the drop down menu (or press Ctrl-N). In this window, all the source code will be executed immediately, and only the explicitly printed values and text is shown in the interpreter shell.

 

1.5 The first Python program

 

So the last thing to do in this chapter is to make your first actual Python program. Let’s open a new editing window, and on that screen write the following two commands. Pay attention to the details, the commands must be written exactly as shown here:

print(“This is our first Python program,”)

and

print(“Hello World!”)

After this, the source code has to be saved by selecting a drop-down menu “File” and “Save as”. In this window the name of the new source code file is given. For this example “hellocode.py” will do nicely. Please pay attention to the file extension name “.py”, which tells the system that this file contains Python code, similarly as “.doc” would tell the system that the file is a Microsoft Word document, or “.png” that the file is a picture. Also, if IDLE opens up a dialog window, where it suggests adding a line “# -*- coding: cp1252 -*-” to the file, select “edit my file”. This is triggered by IDLE identifying non-English characters in the source code file, making it want to add a comment to the file telling the interpreter which code page the code should use. This does not change the behavior of the program in any way, and it is only meant to help the interpreter print these special characters (Ä,É,Ö for example) correctly.

If the interpreter does not understand the character it is supposed to print, it may come out a garbled mess, like “&?a” or “⣔ for “Ä”. There is no easy cure for this problem, but this is not in any way harmful for the program, only an aesthetic nuisance.

The last thing to do is to ask the interpreter to execute the program and run the written source code through the interpreter. However, before doing this, ensure one last time that the written code looks exactly like this, without any indentation and,  character by character, verbatim to the following:

print(“This is our first Python program,”)

print(“Hello World!”)

In Python — and really in any programming language — the commands have to always be written correctly for them to work. The Python commands are always written only in small letters — not Print, PRINT or pritn but print — as the letter size is a meaningful difference for the interpreter, and the interpreter does not try to guess when encountering a typo. It gives an error message and terminates the program. Also, quotation marks and brackets have to be at both ends of both commands.

If everything is in order, select “Run” and “Run Program” from the drop-down menu (hotkey F5). If the interpreter or IDLE gives an error at this point, something is written incorrectly. Otherwise the following printout should appear in the interpreter shell:

>>>
This is our first Python program,
Hello World!
>>>

Example 1-1: The first Python program

Source code                                                                                                            

01  # -*- coding: cp1252 -*-
02
03
print("This is our first Python program,")
04 print("Hello World!")

Output

>>> 
This is our first Python program,
Hello World!
>>> 

The next task is to try this on your own, by doing a similar exercise in the Viope editor and interpreter, and then, in the next chapter, to start learning actual Python programming.

Design a site like this with WordPress.com
Get started