Getting started - Python in easy steps (2014)

Python in easy steps (2014)

1

Getting started

Welcome to the exciting world of the Python programming language. This chapter demonstrates how to install Python and create your first program.

Introducing Python

Installing Python on Windows

Installing Python on Linux

Meeting the interpreter

Writing your first program

Employing variables

Obtaining user input

Correcting errors

Summary

Introducing Python

Python is a high-level (human-readable) programming language that is processed by the Python “interpreter” to produce results. Python includes a comprehensive standard library of tested code modules that can be easily incorporated into your own programs.

The Python language was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. Python is derived from many other languages, including C, C++, the Unix shell and other programming languages. Today, Python is maintained by a core development team at the Institute, although Guido van Rossum still holds a vital role in directing its progress.

image

Discover all the latest Python news online at www.python.org

The basic philosophy of the Python language is readability, which makes it particularly well-suited for beginners in computer programming, and it can be summarized by these principles:

•Beautiful is better than ugly

•Explicit is better than implicit

•Simple is better than complex

•Complex is better than complicated

•Readability counts

As Python is intended to be highly readable it uses English keywords frequently where other languages may use punctuation. Most significantly, it uses indentation to group together statements into code “blocks” whereas other languages may use keywords or punctuation for this purpose. For example, in the Pascal programming language blocks start with the keyword begin and end with the keyword end, and in the C programming language blocks are enclosed within curly brackets ({ } braces). Grouping blocks of statements by indentation is sometimes criticized by programmers familiar with languages that group by punctuation but the use of indentation in Python certainly produces code that has an uncluttered visual layout.

image

Programming languages that group blocks by indentation are said to adhere to the “offside rule” - a pun on the offside rule in soccer.

Some of Python’s key distinguishing features that make it an attractive choice of language for the beginner include:

Python is free - is open source distributable software

Python is easy to learn - has a simple language syntax

Python is easy to read - is uncluttered by punctuation

Python is easy to maintain - is modular for simplicity

Python is “batteries included” - provides a large standard library for easy integration into your own programs

Python is interactive - has a terminal for debugging and testing snippets of code

Python is portable - runs on a wide variety of hardware platforms and has the same interface on all platforms

Python is interpreted - there is no compilation required

Python is high-level - has automatic memory management

Python is extensible - allows the addition of low-level modules to the interpreter for customization

Python is versatile - supports both procedure-orientated programming and object-orientated programming (OOP)

Python is flexible - can create console programs, windowed GUI (Graphical User Interface) applications, and CGI (Common Gateway Interface) scripts to process web data

image

Python is named after the British television comedy series “Monty Python’s Flying Circus” - you may encounter references to this in the Python documentation.

As development of Python continues newer versions are released as with most software. Currently, the final 2.7 version is out, with a statement of extended support for this end-of-life release. The 2.x branch will see no new major releases after that.

The 3.x branch is under active development and has already seen several stable releases. This means that all recent standard library improvements, for example, are only available in Python 3.x. This book describes and demonstrates features of the present and the future of Python with the latest 3.x version.

image

Python 3.x is not backward compatible with Python 2.7.

Installing Python on Windows

Before you can begin programming in the Python language you need to install on your computer the Python interpreter and the standard library of tested code modules that comes along with it. This is available as a free download at http://python.org/downloads For Windows users there is an MSI installer available in both 32-bit and 64-bit versions.

image

Installers for Mac OS X in both 32-bit and 64-bit versions are also available for download at python.org/downloads

imageLaunch a web browser then navigate to python.org/downloads and download the appropriate installer version for your system - in this example it’s an installer file snappily named “Python 3.3.2 Windows X86-64 MSI Installer”

imageWhen the download completes run the installer and choose whether to install for all users or just yourself, then click the Next button to proceed

imageNow, accept the suggested default installation location, which will be a directory on your root C:\ drive named “Python” and version number - in this example it’s a directory at C:\Python33 for Python version 3.3.2

image

image

Support for MSI installer files is included with all recent versions of Windows and free from microsoft.com/downloads - search for “Windows Installer”.

imageClick the Next button to proceed, then be sure to select the feature to “Add python.exe to Path”

image

imageClick on Next to begin copying files onto your computer then click the Finish button to complete the installation

imageTo confirm Python is now available restart your computer, launch a Command Prompt window (run cmd.exe) and enter the exact command python -V - the Python interpreter should respond with its version number

image

image

Ensure that all features in the Customize Python dialog are selected for installation - as illustrated here.

image

The letter V in the command must be uppercase. Ensure the command responds with the version number before proceeding to the examples in this book.

Installing Python on Linux

Linux distributions will, typically, include Python but generally have the 2.7 version as their default. For development on the 3.x branch of Python releases you will probably have to install the latest release alongside the default version.

image

Consult your Linux distro’s documentation for further help on installing Python.

imageLaunch a terminal window and precisely enter this command to reveal the installed default Python version python -V

image

imageNext, precisely enter this command to reveal the default version of a Python 3.x branch, if any is installed python3 -V

image

imageNow, launch your Linux system’s package manager to see if a later Python version is available for installation - for example use the Software Center on Ubuntu systems

image

image

Don’t remove the default 2.7 version of Python from your system in case some applications depend upon it.

imageSearch for “python” in the package manager to see what Python versions and components are installed or if later versions are available for installation

image

imageFinally, install the latest version of the Python 3.x branch - in this case it’s Python 3.3

imageTo confirm the latest version of Python is now available on your computer launch a Terminal window and precisely enter this explicit command python3.3 -V

image

image

You may also, optionally, install IDLE for Python 3.3 but this is not an absolute requirement as the Python programming examples in this book are all created in a plain text editor such as Nano.

image

You can now use the command python3.3 to have that version of the Python interpreter process your programs.

Meeting the interpreter

The Python interpreter processes text-based program code and also has an interactive mode where you can test snippets of code and is useful for debugging code. Python’s interactive mode can be entered in a number of ways:

•From a regular Command Prompt - simply enter the command python to produce the Python primary prompt >>> where you can interact with the interpreter

image

image

•From the Start Menu - choose “Python (command line)” to open a window containing the Python >>> primary prompt

image

image

•From the Start Menu - choose “IDLE (Python GUI)” to launch a Python Shell window containing the Python >>> primary prompt

image

image

Irrespective of the method used to enter interactive mode the Python interpreter will respond in the same way to commands entered at its >>> primary prompt. In its simplest form the interpreter can be used as a calculator.

imageEnter Python interactive mode, using any method outlined opposite, then type a simple addition and hit Return to see the interpreter print out the sum total

image

image

Spaces in expressions are ignored so 8+4 can be also be entered with added spaces for clarity - as illustrated here.

The Python interpreter also understands expressions so parentheses can be used to give higher precedence - the part of the expression enclosed within parentheses will be calculated first.

imageNext, at the Python prompt enter an expression with three components without specifiyng any precedence order

image

imageNow, at the Python prompt enter the same expression but add parentheses to specify precedence order

image

image

Interactive mode is mostly used to test snippets of code and for debugging code.

image

“IDLE” is an acronym for Python’s Integrated DeveLopment Environment but has limited features so is not used to demonstrate examples in this book.

Writing your first program

Python’s interactive mode is useful as a simple calculator but you can create programs for more extensive functionality. A Python program is simply a plain text file script created with an editor, such as Windows’ Notepad, that has been saved with a “.py” file extension. Python programs can be executed by stating the script file name after the python command at a terminal prompt.

The traditional first program to create when learning any programming language simply prints out a specified greeting message. In Python, the print() function is used to specify the message within its parentheses. This must be a string of characters enclosed between quote marks. These may be “ ” double quote marks or ‘ ’ single quote marks - but not a mixture of both.

image

Don’t use a word processor to create program files as they add format information to the file.

imageOn Windows, launch any plain text editor such as the Notepad application

image

hello.py

imageNext, precisely type the following statement into the empty text editor window
print( ‘Hello World!’ )

imageNow, create a new directory at C:\MyScripts and save the file in it as hello.py

image

imageFinally, launch a Command Prompt window, navigate to the new directory and precisely enter the command python hello.py - to see the Python interpreter run your program and print out the specified greeting message

image

image

The directory created at C:\MyScripts will be used to contain all Windows examples in this book.

The procedure to create the traditional first Python program is identical on Linux systems to that on Windows systems. It is, however, important to be aware, on any platform, where different versions of Python are installed; you must use the correct command to call upon the particular Python interpreter required. This is especially important on Linux systems that often ship with the Python 2.7 version installed as their default. This means that the command python will assume you want to call that interpreter. Where Python 3.3 is installed, and you want to call that particular interpreter to process a script, you must use the command python3.3 to explicitly call upon that version’s interpreter.

imageOn Linux, launch any plain text editor such as the Nano application

image

hello.py

imageNext, precisely type the following statement into the empty text editor window
print( ‘Hello World!’ )

imageNow, save the file in your home directory as hello.py

image

imageFinally, launch a Terminal window and navigate to your home directory and precisely enter the command python3.3 hello.py - to see the Python interpreter run your program and print out the specified greeting message

image

image

All further examples in this book are illustrated on Windows (simply because that platform has most users) but they can also be created and executed on Linux.

Employing variables

In programming, a “variable” is a container in which a data value can be stored within the computer’s memory. The stored value can then be referenced using the variable’s name. The programmer can choose any name for a variable, except the Python keywords listed on the inside front cover of this book, and it is good practice to choose meaningful names that reflect the variable’s content.

image

String data must be enclosed within quote marks to denote the start and end of the string.

Data to be stored in a variable is assigned in a Python program declaration statement with the = assignment operator. For example, to store the numeric value eight in a variable named “a”:

a = 8

The stored value can then be referenced using the variable’s name, so that the statement print( a ) will output the stored value 8. That variable can subsequently be assigned a different value, so its value can vary as the program proceeds - hence the term “variable”.

In Python programming, a variable must be assigned an initial value (“initialized”) in the statement that declares it in a program - otherwise the interpreter will report a “not defined” error.

Multiple variables can be initialized with a common value in a single statement using a sequence of = assignments. For example, to initialize variables named “a”, “b” and “c” each with a numeric value of eight like this:

a = b = c = 8

Alternatively, multiple variables can be initialized with differing values in a single statement using comma separators. For example, to initialize variables named “a”, “b” and “c” with numeric values of one, two and three respectively like this:

a , b , c = 1 , 2 , 3

Some programming languages, such as Java, demand you specify what type of data a variable may contain in its declaration. This reserves a specific amount of memory space and is known as “static typing”. Python variables, on the other hand, have no such limitation and adjust the memory allocation to suit the various data values assigned to their variables (“dynamic typing”). This means they can store integer whole numbers, floating-point numbers, text strings, or Boolean values of True or False as required.

image

Programming languages that require variable types to be specified are alternatively known as “strongly typed” whereas those that do not are alternatively known as “loosely typed”.

Optionally, comments can be added to your Python scripts to describe the purpose of statements or sections of code if preceded by a # hash character. Everything following the # hash character up to the end of the line is ignored by the Python interpreter. It is useful to comment your code to make its purpose clear to others or when revisiting the code yourself later.

imageLaunch a plain text editor then declare and initialize a variable - then display its stored value
# Initialize a variable with an integer value.
var = 8
print( var )

image

var.py

imageNext, assign a new value and display that stored value
# Assign a float value to the variable.
var = 3.142
print( var )

imageNow assign a different value and display the stored value
# Assign a string value to the variable.
var = ‘Python in easy steps’
print( var )

imageFinally, assign another value and display the stored value
# Assign a boolean value to the variable.
var = True
print(
var )

imageSave the file in your scripts directory then open a Command Prompt window there and run the program - to see the stored values output as the program proceeds

image

image

Multi-line comments can be added to a script if enclosed between triple quote marks “““...””” .

Obtaining user input

Just as a data value can be assigned to a variable in a Python script, a user-specified value can be assigned to a variable with the Python input() function. This accepts a string within its parentheses that will prompt the user for input by displaying that string then wait to read a line of input.

User input is read as a text string, even when it’s numeric, and can be assigned to a variable using the = assignment operator as usual. Like any other variable value, that assigned by a user can be displayed by specifying the variable name to the print() function - to reference that variable’s stored value.

Multiple values to be displayed can be specified to the print() function as a comma-separated list within its parentheses.

imageLaunch a plain text editor then declare and initialize a variable by requesting user input
# Initialize a variable with a user-specified value.
user = input( ‘I am Python. What is your name? : ‘ )

image

input.py

imageNext, display a response message confirming the input by referencing the stored user name
# Output a string and a variable value.
print( ‘Welcome’ , user )

imageNow, save the file in your scripts directory then open a Command Prompt window there and run this program - enter your name then hit Return to see the response message include your name

image

image

Notice that the prompt string ends with a space that is displayed in output - so the user entry is separated from the colon when typed in.

When multiple values are specified to the print() function it will display each value in output separated by a single space by default. An alternative separator can, however, be specified by adding a sep parameter to the comma-separated list. For example sep = ’*’ will display each value in output separated by an asterisk character.

image

You can explicitly specify a newline to the end parameter, for example end=’!\n’ adds both an exclamation mark and a newline character.

Output displayed by the print() function will, by default, add an invisible \n newline character at the end of the line to automatically move the print head to the next line. An alternative line ending can, however, be specified by adding an end parameter to the comma-separated list. For example,end = ’!’ will display each value in output then end the line with an exclamation mark.

imageEdit the script to declare and initialize a second variable by requesting more user input
# Initialize another variable with a user-specified value.
lang = input( ‘Favorite programming language? : ‘ )

imageNext, display a response message confirming the input by referencing the stored language name - and specifying a custom separator and a custom line ending
# Output a string and a variable value.
print( lang , ‘Is’ , ‘Fun’ , sep = ‘ * ‘ , end = ‘!\n’ )

imageNow, save the file once more, then open a Command Prompt window there and run this program again - enter your name and a programming language then hit Return to see the response message include your user input

image

image

You can include space characters around the separator character for clarity - like those shown around the asterisk character in this example.

Correcting errors

In Python programming there are three types of error that can occur. It is useful to recognize the different error types so they can be corrected more easily:

Syntax Error - occurs when the interpreter encounters code that does not conform to the Python language rules. For example, a missing quote mark around a string. The interpreter halts and reports the error without executing the program

Runtime Error - occurs during execution of the program, at the time when the program runs. For example, when a variable name is later mis-typed so the variable cannot be recognized. The interpreter runs the program but halts at the error and reports the nature of the error as an “Exception”

Semantic Error - occurs when the program performs unexpectedly. For example, when order precedence has not been specified in an expression. The interpreter runs the program and does not report an error

image

Programming errors are often called “bugs” and the process of tracking them down is often called “debugging”.

Correcting syntax and runtime errors is fairly straightforward, as the interpreter reports where the error occurred or the nature of the error type, but semantic errors require code examination.

imageLaunch a plain text editor then add a statement to output a string that omits a closing quote mark
print( ‘Python in easy steps )

image

syntax.py

imageSave the file in your scripts directory then open a Command Prompt window there and run this program - to see the interpreter report the syntax error and indicate the position in the code where the error occurs

image

image

Typically, the syntax error indicator points to the next character after an omission in the code.

imageInsert a quote mark before the closing parenthesis to terminate the string then save the file and run the program again - to see the error has been corrected

imageNext, begin a new program by initializing a variable then try to output its value with an incorrect variable name - to see the interpreter report a runtime error
title = ‘Python in easy steps’
print( titel )

image

image

runtime.py

imageAmend the variable name to match that in the variable declaration then save the file and run the program again - to see the error has been corrected

imageNow, begin a new program by initializing a variable then try to output an expression using its value without explicit precedence - to see a possibly unexpected result of 28
num = 3
print( num * 8 + 4 )

image

image

semantic.py

imageAdd parentheses to group the expression as 3 * ( 8 + 4 ) then save the file and run the program again - to see the expected result of 36, correcting the semantic error

image

Details of how to handle runtime Exception errors in your script code are provided here.

Summary

•Python is a high-level programming language that is processed by the Python interpreter to produce results

•Python uses indentation to group statements into code blocks, where other languages use keywords or punctuation

•Python 2.7 is the final version of the 2.x branch of development but the 3.x branch has the latest improvements

•Windows users can install Python with an MSI installer and Linux users can install Python with their package manager

•The Python interpreter has an interactive mode where you can test snippets of code and is useful for debugging code

•A Python program is simply a text file created with a plain text editor and saved with a “.py” file extension

•The Python print() function outputs the string specified within its parentheses

•String values must be enclosed between quote marks

•Where multiple versions of Python are installed on the same system it is important to explicitly call the desired interpreter

•A Python variable is a named container whose stored value can be referenced via that variable’s name

•A Python variable can contain any data type but must be given an initial value when it is declared

•The Python input() function outputs the string specified within its parentheses then waits to read a line of input

•Syntax errors due to incorrect code are recognized by the interpreter before execution of the program

•Runtime errors due to exceptions are recognized by the interpreter during execution of the program

•Semantic errors due to unexpected performance are not recognized by the interpreter