An Introduction to Python Part 1

An Introduction to Python Part 1

By Jeff Tranter

Qt programmers traditionally program in the C++ language. It offers a number of benefits, including performance, the ability to do systems programming and to scale from small to very large systems. But the language is quite complex. My copy of the book The C++ Programming Language, 4th edition has 1,346 pages!

Scripting languages are less cumbersome, offering a number of advantages, including more widespread familiarity among developers, that can make them attractive for certain applications. For instance, most Qt developers are likely familiar and comfortable with the JavaScript language that has long been supported by Qt, most notably within the QML declarative language.

Python is arguably the most popular scripting language. In this series of blog posts I will cover Python basics, including a brief look at how to develop object-oriented graphical Qt-based applications in Python.

In this first installment I'll give you an overview of Python and its history, offer some programming examples and discuss some of the basic concepts, including variables and objects and the built-in data types and operators.

About Python

Python is a high-level, general-purpose, interpreted programming language. The design emphasizes code readability, and it is intended to be suitable for both small and large-scale programming. Python supports object-oriented or procedural styles of coding and key attributes include dynamic typing, automatic memory management, and a large standard library. Python is cross-platform and is released under an Open Source license.

History

Originally developed by Guido van Rossum in 1991, the name was inspired by the British television series Monty Python's Flying Circus. It is licensed under the Python Software Foundation License, which is a BSD-style, non-copyleft license that allows modifications to the source code, as well as creation of derivative works, without making the modified code open source. The current version is 3.5.1, with a 3.6 release expected at the end of this year.

Pros and Cons

I consider the major strengths of Python to be its emphasis on readability (particularly when contrasted with other scripting languages such as Perl and Tcl), support for object-oriented programming, and its large standard library and third-party modules. Python is available for many platforms and is widely known and used.

As an interpreted language, Python does not require any compiling (or in the case of embedded systems, cross-compiling). Python provides high-level types and data structures, such as complex numbers and associative arrays.

A popular language, Python is used by everyone  from beginning programmers on the Raspberry Pi platform to the authors of articles on computer security in technical journals.

Python’s disadvantages can include performance (due to using an interpreter) and it may not be suitable for very small, embedded systems. However, it is surprisingly small. On my Linux desktop system, the Python binary is just 3.4 megabytes and does not depend on many third-party libraries. There also is a variant called PyMite that is small enough to run on Arduino microcontrollers.

Another drawback: the use of dynamic typing can mean that code requires more testing as some errors may only show up at run time. Some people object to the use of whitespace for indentation, although in my experience programmers generally like this feature once they start actually using it.

Versions 2 and 3 are both maintained in parallel and some users have resisted moving to version 3 because it is not fully backwards compatible and porting is not always trivial. In addition, security can be a concern since you generally have to ship source code in order to execute it, although there are some Python compilers and tools to obfuscate scripts.

An Interactive Example

Python can run in interactive mode where you enter statements and they are executed. You can even create functions in interactive mode. This can be useful for learning and debugging. Below is a sample interactive session illustrating some language features. The commands I typed appear in bold.

% python3
Python 3.4.3 (default, Oct 14 2015, 20:33:09) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, world!")
Hello, world!
>>> print(1+2)
3
>>> print("1+2 =", 1+2)
1+2 = 3
>>> 1+2
3
>>> i=100
>>> i
100
>>> s="hello"
>>> s
'hello'
>>> t='world'
>>> t
'world'
>>> # a comment
>>> 3.2 ** 10
112589.99068426246

 

Note that the information and examples presented here refer to Python 3, although most work the same way with Python 2.

Basics

You can specify a Python script filename on the command line, otherwise it runs interactively as in the example above. Programs consist of statements, one per line. The "#" character starts a comment line. A semicolon (";") is used to separate multiple statements on the same line. The language is case sensitive. Indentation using whitespace defines a block of statements. Definitions, conditionals, and loops end with a colon (":").

The syntax is somewhat like the C and C++ languages. Assignment uses an equals sign and quality uses two equals signs.

Standalone Program Example

Below is a more complete example of a short Python program that defines a function to calculate the factorial of a number:

#!/usr/bin/env python3
import sys

def factorial(n):
    if n > 1:
        return n * factorial(n-1)
    else:
        return 1

print(factorial(int(sys.argv[1])))


This could be put in a file such as factorial.py. You can then run it directly on a Linux or Windows system:

% ./factorial.py 20

2432902008176640000

 

We’ll come back to this example and add some error checking later in the series when we talk about exception handling.

Variables and Objects

Python uses dynamic typing where you don't declare types, rather they are inferred and can change at run-time. Here are some examples:

x = 2
x = 'hello'

 

You can cast from one type to another by specifying the type, e.g. int("12").

Python is not an untyped language -- objects have types but they can change. You can use the type() built-in function to identify an object’s type.

Data Types - Numeric

Numeric types include bool, int, float, Decimal, and complex. (You need to use the statement "import decimal" to use the Decimal type.) A separate long type was removed in Python 3.

It is similar to C/C++ as far as literals and operators, although there are some differences. For instance, "**" is exponentiation, which should make FORTRAN programmers happy. The statements below are all valid assignments:

i = 1234
f = 1.2e12
h = 0xdeadbeef

 

The special value None is used to represent objects that have an undefined type or value.

Data Types - Strings

Like Qt, Python uses Unicode for encoding strings (in UTF-8 format by default). You can use single or double quotes for string literals and can specify multi-line strings in triple quotes. There are many built-in string functions and operators. Below are some examples of string assignment:

s = 'hello'
t = "\nworld"

 

There is no separate character type -- you can just use a string with one character. There is a separate bytes type for working with binary data.

Strings - Indexing

Characters within a string can be returned using the index operator. For example, s[n] returns the nth character in the string s where the first character has index 0. Negative indices are used to index characters from the end or rightmost side of the string (-1 is the last or rightmost character).

Strings - Slicing

Slicing is an operator which returns a substring and uses the format s[i:j]. The first number, i, is the start index, and defaults to 0. The second number, j, is the end index (which is excluded in the returned slice) and defaults to the end. Below are some examples run in interactive mode demonstrating string slicing:

>>> s = "Python Language"
>>> s[0]
'P'
>>> s[1]
'y'
>>> s[-1]
'e'
>>> s[0:]
'Python Language'
>>> s[0:4]
'Pyth'
>>> s[7:11]
'Lang'
>>> s[7:]
'Language'

Operators

The standard operators are similar to C++ with some additional ones. They are listed here ordered by precedence from high to low.         

** Exponentiation (raise to the power)
~ + - Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << Right and left bitwise shift
& Bitwise AND
^ | Bitwise exclusive OR and regular OR
<= < > >= Comparison operators
<> == !=  Equality operators
= %= /= //= -= += *= **= Assignment operators
is, is not Identity operators
in, not in  Membership operators
not, or, and  Logical operators

Summary

I hope you found this short introduction to Python useful and that it may motivate you to consider using this powerful and flexible language. In future blog posts I will cover more of Python’s key features, as well as explore bindings for the Qt framework.