Size: 1211
Comment:
|
Size: 1753
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 5: | Line 5: |
== range and xrange == | == 1. print == In Python 2, `print` is a keyword (as `for`, `if`, etc) {{{#!highlight python sage-8.9: print "hello", 1, 2 hello 1 2 }}} In Python 3, `print` becomes a function {{{#highlight python sage-9.0: print("hello", 1, 2) hello 1 2 }}} Writing a print statement without the parenthesis will result in a `SyntaxError` {{{#highlight python sage: print "hello", 1, 2 File "<ipython-input-9-e91077222f2e>", line 1 print "hello", Integer(1), Integer(2) ^ SyntaxError: invalid syntax }}} == 2. range and xrange == |
Line 28: | Line 50: |
== strings, unicode and bytes == | == 3. strings, unicode and bytes == |
Warning: |
Starting from version 9.0, the default distributed version of Sage is using Python 3. See Python3-Switch for more information. |
Main caveat
1. print
In Python 2, print is a keyword (as for, if, etc)
1 sage-8.9: print "hello", 1, 2
2 hello 1 2
In Python 3, print becomes a function {{{#highlight python sage-9.0: print("hello", 1, 2) hello 1 2 }}} Writing a print statement without the parenthesis will result in a SyntaxError {{{#highlight python sage: print "hello", 1, 2
File "<ipython-input-9-e91077222f2e>", line 1
- print "hello", Integer(1), Integer(2)
- ^
- print "hello", Integer(1), Integer(2)
SyntaxError: invalid syntax }}}
2. range and xrange
In Python range is a function that returns a list.
1 sage-8.9: range(5)
2 [0, 1, 2, 3, 4]
3 sage-8.9: type(range(5))
4 <type 'list'>
In Python 3, range is an object that somehow behave as a list (ie elements can still be acessed with square bracket, it has a length, etc) but it is not a list.
The iterator xrange is no longer valid in Python 3 simply use range instead.
3. strings, unicode and bytes
In Python 2 a chain of characters between simple, double or triple quotes creates an ascii string. To create a unicode string one has to use the prefix u (which remains valid in Python 3).
In Python 3, a chain of characters between quote will gives rise to a unicode string. To create specifically an ascii string one has to use the prefix b (which is already valid in Python 2).