Moving to Python 3 is an essential step for any modern developer. While Python 2.7 was a workhorse for many years, Python 3 introduces crucial improvements, especially in areas like Unicode handling, that make coding more logical and less error-prone. This guide will walk you through the key differences and help you get started on the right foot.
Table of Contents
💻 The `print` Function
The most immediate change you’ll notice in Python 3 is that print
is no longer a statement, but a function. This means it must always be called with parentheses.
- Python 2 syntax (obsolete):
print 'Hello world'
- Python 3 syntax:
print('Hello world')
This change makes the language more consistent. To print without a newline character, you now use the end
parameter inside the function: print('All on', end=' ')
.
💻 Unicode and the `str` vs. `bytes` Distinction
Perhaps the most important reason for Python 3’s existence is its improved handling of text. In Python 3, this distinction is clear:
- The
str
type is now exclusively for Unicode text. It stores a sequence of Unicode codepoints, making it perfect for handling text from any language. - A new
bytes
type was introduced to handle raw binary data.
When you write to a file in binary mode ('wb'
), you must first encode your string into bytes using a method like my_string.encode()
. This separation solves countless bugs and confusion that existed in Python 2.
💻 The Division Operator
Another significant change is the behavior of the division operator /
. In Python 2, dividing two integers would result in an integer (floor division). In Python 3, it always results in a float, which is more intuitive.
- Python 2:
3 / 2
results in1
. - Python 3:
3 / 2
results in1.5
. - To perform floor division in Python 3, you must now use the explicit
//
operator:3 // 2
results in1
.
These core changes make Python 3 a more robust and predictable language to work with.
—
💻 Continue Your Learning Journey
- Python Project Guide: Using Functions in Python 3
- Python Project Guide: Build an FTP Client & Server
- Python Project Guide: Making Scripts
- Python Project Guide: Times, Dates & Numbers
- Python Project Guide: NumPy & SciPy: For Science!
More Topics
- Python Project Guide: NumPy & SciPy: For Science!
- Python Project Guide: Times, Dates & Numbers
- Python Project Guide: Making Scripts
- Python Project Guide: Build an FTP Client & Server
- Python Project Guide: Using Functions in Python 3
- Coding Concepts Explained: Avoid Common Coding Mistakes
- Coding Concepts Explained: The Magic of Compilers