Getting started with Python
So you’d like to give Python a go. How do you start?
(If you are going to be using Python for Scientific Computing, including Data Analysis, have a look at this article instead)
Make sure you install Python 3, which is the modern version of Python. There is also a legacy version of Python, Python 2.7, but this is being phased out and should not be used for new projects.
You can find installation files for Windows and Mac OSX at https://www.python.org/downloads/. When you start the installation on Windows there will be an option to add Python to the system path. I recommend you select this option, as it makes it easier to run your Python scripts. I have not tried this on Mac OSX; it may have the same option.
For Linux you can use your software package manager, such as aptitude, yum or zypper to install ‘python3’. This will give you Python 3
Running Python – REPL/Console
For trying out some simple Python commands you can use the Python Console. This is also called the REPL (Read, Execute, Print Loop). To start the Python Console, just run Python. This will give you something like this:
Have a little play with this. For instance:
When you are done, press ^Z (Windows) or ^D (Mac OSX and Linux). Or enter ‘exit()’
Running Python – IDLE editor
The console is great for quick experiments. For anything more permanent it is better to create a script, a text file which contains Python code. When you installed Python it came with IDLE, a very simple integrated development environment.
Start IDLE from your operating system’s menu. You will see something like this:
Now select File, New File. Enter some Python commands, like:
Hit ‘F5’ to run the program. You will be prompted to save the file first, so give it a name and save it. You will see the result of your script in the original (shell) window:
Running a Python script from the command line
Say you’ve written a Python script, or someone else has given you a script. How do you run it?
- Start a Terminal or (as Windows calls it) a Command Prompt.
- Use the ‘cd <path to folder>’ command to go to the folder which contains the script
- Enter: ‘python <scriptname>.py’. For instance: ‘python test.py’
IDLE is great for getting you started quickly, but for any serious Python development I suggest you use a professional text editor or IDE (Integrated Development Environment). Both a text editor and an IDE let you create and edit text files. An IDE can also run, debug, test and more. For instance:
- PyCharm. My favourite IDE. It gives you so much power to write, run, debug and test your scripts, I don’t know where to start. Just check it out at …. Start with the free Community edition.
- Visual Studio Code. I hear good things about this IDE, and it recently became more popular than PyCharm, so it must be doing something right.
- Sublime Text. An excellent text editor