Welcome! This tutorial details how to get started with Python. It’s written/edited/updated by Derrick Kearney (Canadian, Python master, foodie) and Michael Herman (from the Real Python team, of course).
I (Derrick) help administer several Python groups where I field countless questions each day. In this post I’ll answer the question I hear the most, “How do I get started with Python?”.
(1) What is Python?
Python, named after the British comedy group Monty Python, is an interpreted, interactive, object-oriented programming language. Its flexibility allows it to do many things, both big and small. Python can be used to write simple programs, but it also possesses the full power required to create complex, large-scale enterprise solutions. Some of the ways in which Python is used includes:
- Desktop graphical application development, including games;
- Mathematical and scientific analysis of data; and,
- Web and internet development.
Python’s presence in the world of computer programming can be found everywhere. For example, Python is used in some of the largest internet sites on earth – like Reddit, Dropbox, and Youtube, to name a few. The popular Python web framework Django powers both Instagram and Pinterest. LucasFilms’s award winning visual effects company, Industrial Light & Magic, uses Python to make help make their magic come to life.
It’s easy to forget just how powerful Python is because it’s so easy to learn.
- Strongly typed. It enforces data types so you can’t concatenate a string and a integer, for example.
- Dynamically, implicitly typed. So, you don’t have to explicitly declare variable data types. Data types are enforced at runtime.
- Case sensitive. For example,
TOKENare two different variables.
- Object-oriented. Everything is an object.
(2) Getting Python – a prelim
Python is free, open-source software that works on Linux, Mac, Windows, and various other platforms (21 in total). It comes preinstalled on Mac and most distributions of Linux; however, you may need to download the latest version (see below). To check your version, open the terminal and run the command
Choosing a Python Version
It can be confusing for both new and seasoned programmers on deciding between Python 2 or 3. Fortunately, there are few syntactical differences between the two and you can run both version on your computer.
Currently, there are two main versions of Python – 2.x and 3.x.
Only version 3.5.x is in active development, in terms of gaining new features and functionality, while Python 2.7.x as well as 3.2.x to 3.4.x are actively maintained.
Which version is right for you? Well, that’s up to you. Honestly, there are few differences between the two that will affect you at this early stage, so either choice will suffice. Plus, once you’ve learned one, it’s not too difficult to learn the other.
In general, if you’re just starting to learn Python, go with 3.4.x, since it’s a better version as there are added features along with plenty of bug fixes and refinements. However, 2.7x has much more support from third-party libraries. If you know you’ll need to use a library that has not been ported to version 3.4.x, then it may be best to start with 2.7x.
The examples in this series will be shown in version 3.4.2, which is the current version as of writing. That said, most of the examples will work fine with either version since many of the features and updates added to 3.4.x were also added to 2.7.x. We’ll discuss any differences that you should be aware of as they arise.
(3) How do I get Python?
Regardless of your operating system, you can download Python from the Python Software Foundation (PSF). Grab the version specific to your OS and processor (32 or 64-bit).
- Mac: I strongly recommend using Homebrew to install and manage different version of Python. Check out the directions here. You can also download Python from the PSF.
- Linux: Again, Python is included on various flavors of Linux. Be sure to upgrade to the latest version using the package manager, if necessary.
- Windows: Download Python direct from the PSF.
Windows users: Make sure you select the option to add Python to your system path during the installation process:
(From the drop-down select the option, “Will be installed on local hard drive”.)
(4) Confirming the Python Install
Let’s do a quick sanity check to ensure Python installed correctly.
Open the Python Interactive Shell:
- Mac: Open your terminal and run:
python3, depending upon your installation.
- Linux: Open your terminal and run:
- Windows: If you have only one version of Python installed simply run
python. If you have both Python 2.7 and Python 3 installed, run
pythonfor Python 2.7 and/or
py -3for Python 3.
Windows users: Ensure that your account has administrative privileges: Run the command prompt at an elevated level by right-clicking the command prompt icon, and then selecting ‘Run as Administrator’.
The interactive Python Shell should open, and your command prompt or terminal window should look similar to this:
1 2 3 4
While you’re here, you might as well run your first line of code…
If you’re running Python 2.x, the
You should see:
And that’s it: You’ve just written your first Python program! Each time you entered a line, Python immediately executed the statement, displaying the value between the quotes.
Once done, you can use
exit() to leave the Python Shell. Or:
- Mac and Linux users: Ctrl-D plus Return
- Windows users: Ctrl-Z plus Return
Keep your terminal or command prompt open. We still have more to do! Let’s continue using the Shell as we run through the Python primitives.
(5) Language Primitives
In this section we’ll look at the Python primitives – variables, built-in data types, comments, syntax, and semantics.
Variables are containers for data. The syntax to declare them is:
variable_name = variable_value. While you can name variables anything you’d like (except for a few reserved keywords), you should use a naming scheme that makes intuitive sense. The variable name should provide some indication as to what the values assigned to it are.
For example, many new programers, use simple variable names like
y. Do (err, try) not to do this. Instead, if you have two numbers – say
52 – use the variable names
num2 instead of
y. That way when others read your program, they can make an educated guess that
num2 are probably numbers of some sort. Think of others when writing your programs, as well as your future self. Your future self will thank you.
Built-in Data Types
Python has a number of built-in data types such as numbers (integers, floats, complex numbers), strings, lists, tuples, and dictionaries.
Each of these can be manipulated using:
- Data-type methods
Be sure to type each example out along with me.
Numbers can be integers, floating points, Booleans, or complex numbers. The former three are the most important:
- Integers are whole numbers –
- Floats have decimal points –
- Booleans represent either
0). They represent data that can only be one thing or another.
You’ve seen operators before. They’re things like addition (or concatenation) and subtraction, just like you learned in Elementary school.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Putting your pre-algebra skills to the test, let’s look at comparisons, which evaluate to boolean values – e.g., either
1 2 3 4 5 6 7 8 9 10 11 12
Python provides you with a number of built-in functions for manipulating integers. These are always available to you. Please note: These functions can be used on any data type. There are a number of modules available in the Python Standard Library as well, such as
math. To use the functions associated with these modules, you’ll first have to import the module. More on this later. For now, let’s look at a few examples of built-in functions.
float() – given an integer, this function returns a float.
1 2 3 4
int() – given a float, this function returns and integer. This function does NOT round the input up (ceiling) to the nearest integer – it simply throws out anything after the decimal point (flooring) and returns the number. So the input of 10.6 returns 10, NOT 11. Similarly, 3.25 returns 3.
1 2 3 4
Besides functions, there a number of data-type methods associated with each type of number.
float.is_integer() – tests if a float is finite.
1 2 3 4
Strings are lines of text that are declared with single or double quotes:
1 2 3 4 5 6 7 8 9 10 11
Like numbers, you can concatenate strings (string concatenation):
1 2 3 4 5
Let’s look at just a few functions that are good to use for string manipulation:
len() – given a string, this function returns the length of it.
slice() – given a start and stop value, you can access a set of, or single, character(s).
1 2 3 4 5 6 7 8 9
While we’ll only touch on a few data-type methods, be sure to check out the full Python documentation as there are a number of important functions that you should be aware of.
string.capitalize() – returns the string with the first letter capitalized.
1 2 3 4 5
string.format() – you can easily format values into strings.
1 2 3 4 5
string.strip() – returns the string with the leading and trailing whitespace removed.
1 2 3
Lists, which are called Arrays in nearly every other programming language, group various types of data together.
create_a_list = 
numbers_list = [1, 2, 3]
strings_list = ["spam", "eggs", "cheese"]
mixed_list = ["Hello", [1, 2, 3], False]
As you can see above, lists may contain any data type (you can mix and match, too), including other lists or nothing at all. You can access parts of lists just like strings with indexes. The syntax is the same:
1 2 3 4 5 6 7 8 9 10 11 12
You can access elements from the list from either the beginning or end of the list:
1 2 3 4 5 6
Watch how you can create a new list just by accessing the elements:
1 2 3 4
Negative indexes count from the last item backwards:
1 2 3
If you nest a list within another list, you can access the inner list using multiple indexes:
1 2 3
Lists can be concatenated:
1 2 3 4 5
In general, you can think of lists as strings – only each piece of data is an element. What does that mean in practical terms? Well, the same functions you use on strings can be used for lists.
len() – given a list, this function returns the length of it.
1 2 3
slice() – given a start and stop value, you can access a set of elements.
1 2 3 4 5 6 7 8 9
Again, check out the Python documentation to see all available list methods.
list.append() – used to add an item to the end of a list
1 2 3 4
list.sort() – sort this list
1 2 3
list.pop() – given an index value, remove an element from the list
1 2 3 4 5
Tuples are similar to lists, but they are immutable – which means they cannot be changed after creation.
Just like a list, you can also use indexes to access different elements:
1 2 3 4
Often tuples are used for dictionary keys since they should (err, must) be immutable.
Yes, you can add two tuples:
1 2 3 4 5
list() – used to convert a tuple to a list
1 2 3
What about converting a list to a tuple? Is there a function for that? Where would you go to find out?
Because tuples are immutable, many of the list methods don’t work on tuples.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Dictionaries are a type of associative array (an object) implemented using hash tables containing key/value pairs. They are unordered.
You can return a key’s value using the following syntax:
1 2 3 4 5
Research this on your own, using the Python documentation. Need help? Comment below.
Speaking of comments…
Comments are used to describe your code so other developers can quickly understand what’s happening (as well as your future self).
1 2 3
Like a good friend, Python is always available if you get stuck. Perhaps you want to know how a specific object works, simply open the Python shell and then call
help() to get help or
dir() to see which methods are available for that particular object.
(6) Coding in Python
There are three basic approaches to coding in Python. We already used one of them – the interactive Python Shell.
The Shell (redux)
This is the least powerful of the three. Although you can create functions in the Shell, typically it is reserved for simple, one-line statements to get quick feedback on your code.
For example, let’s look at a simple expression. Open the Shell and run:
1 2 3
The Python Shell simply evaluated
24 + 10, adding the two numbers, and outputted the sum,
Try one more:
Take a minute to read the output. These are some important concepts in Python, which will help you write idiomatic Python code.
Close the Python interactive Shell. Once closed, our code is gone. In other words, the code typed into the Python Shell is not persistent – and cannot be reused. As coders, we want code that we can reuse to save precious keystrokes. Unfortunately, the Python Shell fails in this regard.
Python comes with a program named IDLE (named after Monty Python’s Eric Idle). IDLE is interactive and can be used exactly like the Python Shell. It can also be used for code reuse since we can create and save Python code. That said, IDLE still is not as powerful as the last method, so we will skip it for now.
If you are interested in using IDLE check out the excellent guide One Day of IDLE Toying.
The best approach is to use an actual coding editor. Some people prefer an Integrated Development Environment (IDE), but a far simpler code editor is much better for learning purposes.
Why? When you are learning something new you want to peel off as many layers of complexity as possible. Simplify things. By adding a complex IDE into the mix, which you will have to learn how to operate, you are just adding more and more layers, making the task – learning Python – even more difficult.
(7) Picking a Coding Editor
A Python program, in its basic form, is simply lines of text (code) saved in a file with a .py file extension. Python code can be written in something as basic as Notepad – but there’s no reason to put yourself through such an ordeal since there are much better options available. At it’s core, a code editor should provide a number of features that help a programmer create programs (Python scripts and modules, in our case). In most cases, code editors allow the user to customize the program itself, to suit your needs and style.
What should you look for in a code editor?
- Ease of use
- Syntax highlighting
- Tabbed views
- Line numbering
- Ability to customize the look and feel of the editor
- Availability of add-ons
Take a look at the following example:
So, not only is the code easier to read in the editor (Sublime Text) on the top (due to the syntax highlighting and line numbering), but it’s also identifying three simple errors, one of which is a show-stopper. (Can you figure out which one?) Meanwhile, the editor (Notepad) at the bottom does not display the errors and is hard on the eyes since it’s black and while.
Which editor should I use?
One of the most popular code editors is Sublime Text 3 (shown above). It is powerful, cross-platform, and free to try out.
Be sure to support the project by purchasing a license if you continue to use it.
If you want something simpler, check out gedit, which is also cross-platform. Notepad++ is also a great editor, but it’s for Windows only. Both of these editors are free and although neither possesses the power of Sublime Text, they are still useful.
A third option is Vim, which is free and available for Mac, Linux, and Windows. Vim has a steep learning curve but it has a loyal user base. Steve Francia’s Vim Distribution is the best programming setup for Vim that I have ever seen.
I personally prefer Sublime Text 3. Check out the blog post Setting Up Sublime Text 3 for Full Stack Python Development to see how to customize it specifically for writing Python code.
Remember: There are many different options when it comes to code editors, both free and commercial. Do your research, and don’t be afraid to experiment! Just remember: an editor should help you adhere to Python coding standards, practices, and idioms…
(8) Python Idioms = Happy Coding
PEP 8 — Style Guide for Python Code is the style guide for programming Python code. Study this.
One idiom that trips up many new Python developers is indentation. Python uses indentation (4 spaces) to logically organize code into sections called code blocks. A code block starts with an indent and ends with a dedent (un-indent?). Incorrect indentation will generate an error in Python preventing your code from executing. And this is exactly where having a properly setup code editor pays off, since it will catch indentation errors and highlight them for you. You should also use spaces instead of tabs when indenting. Most editors will allow you to convert tabs to spaces, so that when you tab it is actually applying 4 spaces.
Let’s revisit the errors from the above image…
- Line 2 – No space around the
<operator. As explained in PEP8, Python expects spaces around operators. This is not a critical error but problematic as your code should be clean and readable.
- Line 4 – There are two errors here, including the show stopper. As stated above, Python uses indention to define code blocks.
count = count + 1, is part of a block of code that starts on line 2, so that it must be indented 4 spaces in order for Python to include it in the code block.
(9) Counting to 10
Ready to dive into a basic example?!
If you are brand new to programming you may not fully understand the code but it’s the concepts that are important. Python is designed to read very easily and this example demonstrates that principle. We are going to fix the broken code above, and add one more code block to emphasize the concepts of code blocks and indentation.
Many programmers get overwhelmed when they initially approach a problem. An effective approach to help solve the problem, regardless of size, is to logically divide the problem into parts.
For example, let’s code a basic program that counts from 1 to 10. Each time the count increments we want to display a new number, and to help with the concept of code blocks we are going to show what happens after we reach 10. One approach to help in development of a workflow, is to use pseudocode.
Let’s Make a Plan (pseudocode!)
I like to keep things organized on my computer, so first create a folder, put it in your “documents” folder or someplace similar. I created a folder called,
python_code. Learning to code is hands on, so open up your code editor, and enter the following code. Do not copy and paste no matter how tempting it is. Doing so will hinder learning.
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Note that the first line of each example has a
# (hash character), followed by a space and then an explanation. This is an inline comment. Such comments have a number of purposes, but for the most part they are used to either explain code or summarize a specific approach a developer took. Do the comments in the above examples make sense to you? If not, change them.
Finally, as you will soon come to find out, comments are ignored by Python when the code is executed.
Did you notice that the examples use both single
=, and double
==? This can be confusing.
- n the expression
count = 1, the
=assigns the value of 1 to the variable named
- In the conditional
if count == 11:, the
==compares the value of
11, returning a boolean
False. Can you tell what the statement evaluates to in the above example after each iteration?
Save the file as count_to_ten.py in the folder you created then exit the editor. Open a terminal or command prompt and navigate to the folder you created.
Now run the code:
You may need to replace
py -3, depending on your setup. See Step 4 for more info.
And the output should look something like this:
Congrats! You just wrote your first program.
(10) Errors and Exceptions
Errors are something that irritate and frustrate programmers at every level of experience.
In Python, there are two types of code-based errors, syntax errors and exceptions.
We have already seen this error already – incorrect indentation. Syntax errors will prevent execution of the program. In this example, the
if statement is missing a colon to end the statement. As you can see Python is very helpful to point out the error:
1 2 3 4 5 6
Exception errors occur during program execution. Python has a number of built-in exceptions. For example:
1 2 3 4 5
Semantic errors are errors that happen as a result of one or more problems in logic.
These errors can be more complex, because no error is generated. The code runs but generates unexpected and/or incorrect output, or no output. A classic example of this, would be an infinite loop that most new programmers experience at least once.
(11) Python’s Power – Packages/Modules
One of the great things about Python is the plethora of available modules, both built into the Python core and third party packages/libraries – used to extend the language. These modules can be very helpful. Some of the more utilized built-in Python modules include:
- math: mathematical functions from the standard library of the C (you’ve seen this one already)
- random: a pseudo-random number generator
- datetime: used for manipulating dates and times
- re: for working with regular expressions
For example, here we
import math to use
sqrt (square root) and
pow (raising to the power):
Warning: Do not name your Python files the same as a module – like math.py or random.py. This will cause conflicts, resulting in unexpected behavior in your code. So if you are using the math module, do not name your file math.py. Make sense?
The best way to manage Python’s third party packages/modules is with pip. New coders frequently hit a wall when they are following some example code and they see the following error when they try to run the code:
ImportError: No module named MODULE_XXXX.
These modules need to be manually installed using Pip. In Python 3, pip, called pip3, is included. If you used Homebrew to install Python, pip is included as well. Starting with Python 2.7.9, pip is also included. If you are using a Python version prior to 2.7.9, follow these instructions to install pip:
- Download get-pip.py, confirm that the file was saved with a .py extension.
- Navigate to the location of the downloaded file in the Terminal or Command Prompt.
- Read the official pip documentation for more information.
(12) Next Steps
There are plenty of online tutorials, books, and videos freely available.
My first stop was one of the most popular free choices, Learn Python the Hard Way. Zed Shaw’s tutorial is laid out in a progressive and logical exercise format. I found it very useful for learning the syntax, but I needed more.
One of the best ways of learning how to code is by building – the project driven learning approach. That’s how I came across Real Python. There are three Real Python that cost a modest fee, which are frequently updated (usually bi-monthly) to keep up with changes (free of charge).
Another place that truly helped me was MIT’s course, Introduction to Computer Science and Programming, which covers various computer science concepts along with Python. The course can be found in two locations.
- The Harvard and MIT non-profit online initiative (Edx.org) offers the course in two parts. They are challenging and provide an excellent approach to problem solving. Both parts are graded.
- The other route is from the MIT open courseware, Introduction to Computer Science and Programming MIT 6.00x. The course is not graded, but it has a very active online community that is quite helpful.
There are other online courses of course. Again, this is personal choice, so do your own research.
Another source of free learning materials comes from the PSF:
Above all, it is important that you do not fall into finding the “best” book or video search and get lost. Do some research. Ask around. But pick something and stick with it! Open your code editor and start coding! Make a commitment to yourself to complete it.
(13) Riding a Bike
Coding is like riding a bike: You can watch people to see how it is done, and sometimes you can get a push, but in the end it is a solo event. When I get stuck, or need to brush up on a new concept, the first place I go is Google. If I get an error message, typing in the exact error message, into Google, will often bring up a result in the first page that solves my problem.
Check out these resources as well:
- The official Python Docs – Python 2.7 or Python 3
- Tutorials Point has some very simple and easy to follow examples when I need a quick refresh.
- Jeff Knupp’s website (the author of the Idiomatic Python series of tutorials and books)
- The Real Python Blog has more specific topics and advanced subjects like Python’s Web Frameworks, Django and Flask.
- Bernd Klein’s Python Course contains excellent coverage of Python; his discussion of advanced topics is really helpful.
- Stack Overflow, the Q&A for coding, has some great explanations of Python topics. How Python can slice a string, is one truly excellent example.
If you get stuck on a problem, try these simple suggestions:
- Stop coding!
- Get out a piece of paper and map out how to solve the problem using plain words (pseudocode); use a flow chart if necessary. Refer to the example above.
- At some point you will be introduced to Python’s exception handling – the
try/exceptblock. Do not use use a
tryuntil your code is working. The
trycan suppress valuable error messages that help identify problems in code.
- If you are not getting expected output – i.e., perhaps Python is displaying a word instead of a number (incorrect data type) – add a print statement right after the variable assignment and then right before the expected output. This is an effective, quick and dirty problem solver.
- If you are still stumped, a great tool is the Python Visualizer. This tool allows you to ‘step through’ your code as it executes. The Python Visualizer has examples to help you if needed.
- One final note – and this is very important – is that a frustrated brain is not going to help. When you start to get annoyed because something is not working, take a break, clear your brain. Go for a run. Do something else. You will be amazed just how effective this can be. Often, you’ll come back with clear eyes and see a simple typo, a misspelled keyword, etc.
(14) Simple Advice for New Coders
I say this in the nicest kind of way – no one is going to spoon feed you. Coders expect other coders – yes, even beginners – to try and resolve the issue themselves. At some point we all need guidance, though.
Once you have tried and truly have hit the wall ask for help, before you smash your keyboard or other inanimate object(s). There are a number of places to get help – code forums, Facebook Groups, the IRC channel #python, to name a few. Take a minute to read any rules or guidelines for any of the groups that you use. Make it easy for others to help you by explaining the problem and what you have tried. If there is an error, include that information as well.
Have fun coding!
(15) Test your knowledge
- What does it mean that Python is a strong, dynamically typed language?
- How do you access the Python Shell?
- How do you declare a variable?
- What’s the difference between a variable name and a variable value?
- What are Python’s built-in data types?
- What’s the difference between an integer and a floating point number?
- What are boolean values?
- What does the
- What’s the difference between a list and a tuple?
- What’s a dictionary?
- Why should you use comments in your code?
- Test out the
help()function. What did you learn?
- Pass in
dir()function. What did you learn?
- One primitive that we didn’t go over is
None. What does it represent?
- You can check the data type of a variable or a value by using the
type()function. Test this out using various data types and variables. What did you learn?
Open your text editor and create a new file called exercise.py. Copy and paste the following code into the file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
Following the instructions, update the code. When done, run the code from your terminal to test –