The Short Explanation¶
To make your project be single-source Python 2/3 compatible, the basic stepsare:
Only worry about supporting Python 2.7
Make sure you have good test coverage (coverage.py can help;
python-mpipinstallcoverage
)Learn the differences between Python 2 & 3
Use Futurize (or Modernize) to update your code (e.g.
python-mpipinstallfuture
)Use Pylint to help make sure you don't regress on your Python 3 support(
python-mpipinstallpylint
)Use caniusepython3 to find out which of your dependencies are blocking youruse of Python 3 (
python-mpipinstallcaniusepython3
)Once your dependencies are no longer blocking you, use continuous integrationto make sure you stay compatible with Python 2 & 3 (tox can help testagainst multiple versions of Python;
python-mpipinstalltox
)Consider using optional static type checking to make sure your type usageworks in both Python 2 & 3 (e.g. use mypy to check your typing under bothPython 2 & Python 3;
python-mpipinstallmypy
).
Note
Note: Using python-mpipinstall
guarantees that the pip
you invokeis the one installed for the Python currently in use, whether it bea system-wide pip
or one installed within avirtual environment.
Python 3 has been out for over a decade and is widely used around the world. In this course, you will learn how to migrate from Python 2 to Python 3 and how to benefit from Python 3's improved features and performance. If you are on a unix based system (Ubuntu, etc.), and you currently have python 2.x. Go ahead and download the python 3.x from Python.org. After installation it will create a separate directory python3. To run your programs with python2.x use python filename.py. To run your programs with python3.x, use python3 filename.py.
- Notice that I am using Windows 10, Python 2.7.14 an Python 3.6.4. First of all, let's download both versions of Python from the Python download page. I downloaded the files python-2.7.14.msi and python-3.6.4.exe (not sure why the one is.msi and the other is.exe it doesn't matter anyway). Firstly I am installing Python 2.7.14 and selecting.
- 2to3 is a Python program that reads Python 2.x source code and applies a series of fixers to transform it into valid Python 3.x code. The standard library contains a rich set of fixers that will handle almost all code. 2to3 supporting library lib2to3 is, however, a flexible and generic library, so it is possible to write your own fixers for 2to3.
In the following examples, input and output are distinguished by the presence orabsence of prompts (>>> and …): to repeat the example, you must typeeverything after the prompt, when the prompt appears; lines that do not beginwith a prompt are output from the interpreter. Note that a secondary prompt on aline by itself in an example means you must type a blank line; this is used toend a multi-line command.
Many of the examples in this manual, even those entered at the interactiveprompt, include comments. Comments in Python start with the hash character,#
, and extend to the end of the physical line. A comment may appear at thestart of a line or following whitespace or code, but not within a stringliteral. A hash character within a string literal is just a hash character.Since comments are to clarify code and are not interpreted by Python, they maybe omitted when typing in examples.
Some examples:
3.1. Using Python as a Calculator¶
Let's try some simple Python commands. Start the interpreter and wait for theprimary prompt, >>>
. (It shouldn't take long.)
3.1.1. Numbers¶
The interpreter acts as a simple calculator: you can type an expression at itand it will write the value. Expression syntax is straightforward: theoperators +
, -
, *
and /
work just like in most other languages(for example, Pascal or C); parentheses (()
) can be used for grouping.For example:
The integer numbers (e.g. 2
, 4
, 20
) have type int
,the ones with a fractional part (e.g. 5.0
, 1.6
) have typefloat
. We will see more about numeric types later in the tutorial.
Division (/
) always returns a float. To do floor division andget an integer result (discarding any fractional result) you can use the //
operator; to calculate the remainder you can use %
:
With Python, it is possible to use the **
operator to calculate powers 1:
The equal sign (=
) is used to assign a value to a variable. Afterwards, noresult is displayed before the next interactive prompt:
If a variable is not 'defined' (assigned a value), trying to use it willgive you an error:
There is full support for floating point; operators with mixed type operandsconvert the integer operand to floating point:
In interactive mode, the last printed expression is assigned to the variable_
. This means that when you are using Python as a desk calculator, it issomewhat easier to continue calculations, for example:
This variable should be treated as read-only by the user. Don't explicitlyassign a value to it — you would create an independent local variable with thesame name masking the built-in variable with its magic behavior.
In addition to int
and float
, Python supports other types ofnumbers, such as Decimal
and Fraction
.Python also has built-in support for complex numbers,and uses the j
or J
suffix to indicate the imaginary part(e.g. 3+5j
).
3.1.2. Strings¶
Besides numbers, Python can also manipulate strings, which can be expressedin several ways. They can be enclosed in single quotes ('..'
) ordouble quotes ('..'
) with the same result 2. can be usedto escape quotes:
Python 2 To 3
In the interactive interpreter, the output string is enclosed in quotes andspecial characters are escaped with backslashes. While this might sometimeslook different from the input (the enclosing quotes could change), the twostrings are equivalent. The string is enclosed in double quotes ifthe string contains a single quote and no double quotes, otherwise it isenclosed in single quotes. The print()
function produces a morereadable output, by omitting the enclosing quotes and by printing escapedand special characters:
If you don't want characters prefaced by to be interpreted asspecial characters, you can use raw strings by adding an
r
beforethe first quote:
String literals can span multiple lines. One way is using triple-quotes:''..''
or ''..''
. End of lines are automaticallyincluded in the string, but it's possible to prevent this by adding a atthe end of the line. The following example:
produces the following output (note that the initial newline is not included):
Strings can be concatenated (glued together) with the +
operator, andrepeated with *
:
Two or more string literals (i.e. the ones enclosed between quotes) nextto each other are automatically concatenated.
This feature is particularly useful when you want to break long strings:
This only works with two literals though, not with variables or expressions:
If you want to concatenate variables or a variable and a literal, use +
:
Strings can be indexed (subscripted), with the first character having index 0.There is no separate character type; a character is simply a string of sizeone:
Indices may also be negative numbers, to start counting from the right:
Note that since -0 is the same as 0, negative indices start from -1.
In addition to indexing, slicing is also supported. While indexing is usedto obtain individual characters, slicing allows you to obtain substring:
Turntable 3 2 4 x 4. Slice indices have useful defaults; an omitted first index defaults to zero, anomitted second index defaults to the size of the string being sliced.
Note how the start is always included, and the end always excluded. Thismakes sure that s[:i]+s[i:]
is always equal to s
:
One way to remember how slices work is to think of the indices as pointingbetween characters, with the left edge of the first character numbered 0.Then the right edge of the last character of a string of n characters hasindex n, for example:
The first row of numbers gives the position of the indices 0…6 in the string;the second row gives the corresponding negative indices. The slice from i toj consists of all characters between the edges labeled i and j,respectively.
For non-negative indices, the length of a slice is the difference of theindices, if both are within bounds. For example, the length of word[1:3]
is2.
Attempting to use an index that is too large will result in an error:
However, out of range slice indexes are handled gracefully when used forslicing:
Python strings cannot be changed — they are immutable.Therefore, assigning to an indexed position in the string results in an error:
If you need a different string, you should create a new one:
The built-in function len()
returns the length of a string:
See also
Strings are examples of sequence types, and support the commonoperations supported by such types.
Strings support a large number of methods forbasic transformations and searching.
String literals that have embedded expressions.
Information about string formatting with str.format()
.
The old formatting operations invoked when strings arethe left operand of the %
operator are described in more detail here.
3.1.3. Lists¶
Python knows a number of compound data types, used to group together othervalues. The most versatile is the list, which can be written as a list ofcomma-separated values (items) between square brackets. Lists might containitems of different types, but usually the items all have the same type.
Like strings (and all other built-in sequence types), lists can beindexed and sliced:
All slice operations return a new list containing the requested elements. Thismeans that the following slice returns ashallow copy of the list:
Lists also support operations like concatenation:
Unlike strings, which are immutable, lists are a mutabletype, i.e. it is possible to change their content:
You can also add new items at the end of the list, by usingthe append()
method (we will see more about methods later):
Assignment to slices is also possible, and this can even change the size of thelist or clear it entirely:
Python 2 To 3 Translation
The built-in function len()
also applies to lists:
It is possible to nest lists (create lists containing other lists), forexample:
Python 2 To 3 Differences
3.2. First Steps Towards Programming¶
Of course, we can use Python for more complicated tasks than adding two and twotogether. For instance, we can write an initial sub-sequence of theFibonacci seriesas follows:
This example introduces several new features.
The first line contains a multiple assignment: the variables
a
andb
simultaneously get the new values 0 and 1. On the last line this is used again,demonstrating that the expressions on the right-hand side are all evaluatedfirst before any of the assignments take place. The right-hand side expressionsare evaluated from the left to the right.The
while
loop executes as long as the condition (here:a<10
)remains true. In Python, like in C, any non-zero integer value is true; zero isfalse. The condition may also be a string or list value, in fact any sequence;anything with a non-zero length is true, empty sequences are false. The testused in the example is a simple comparison. The standard comparison operatorsare written the same as in C:<
(less than),>
(greater than), (equal to),<=
(less than or equal to),>=
(greater than or equal to)and!=
(not equal to).The body of the loop is indented: indentation is Python's way of groupingstatements. At the interactive prompt, you have to type a tab or space(s) foreach indented line. In practice you will prepare more complicated inputfor Python with a text editor; all decent text editors have an auto-indentfacility. When a compound statement is entered interactively, it must befollowed by a blank line to indicate completion (since the parser cannotguess when you have typed the last line). Note that each line within a basicblock must be indented by the same amount.
The
print()
function writes the value of the argument(s) it is given.It differs from just writing the expression you want to write (as we didearlier in the calculator examples) in the way it handles multiple arguments,floating point quantities, and strings. Strings are printed without quotes,and a space is inserted between items, so you can format things nicely, likethis:The keyword argument end can be used to avoid the newline after the output,or end the output with a different string:
Footnotes
Python 2 To 3 Differences
Since **
has higher precedence than -
, -3**2
will beinterpreted as -(3**2)
and thus result in -9
. To avoid thisand get 9
, you can use (-3)**2
.
Unlike other languages, special characters such as n
have thesame meaning with both single ('..'
) and double ('..'
) quotes.The only difference between the two is that within single quotes you don'tneed to escape '
(but you have to escape '
) and vice versa.