Writing and running Python from an IDE
Python scripts
So far we've worked in the REPL which does not allow us to save our programs.
Instead of the interactive mode, Python can read a file that contains Python instructions. This file is commonly referred to as a Python script.
Python scripts are plain text files. To create a plain text file, you need to use a text editor. When we do programming, typically we will use a special text editor called an IDE, or integrated development environment, that contains lots of tools to help us. We will use Visual Studio Code (vscode), which is a free IDE available for Windows, Mac, and Linux.
Writing text files with Visual Studio Code
Follow these steps:
Create a folder on your computer for the python files you will write later
Open Visual Studio Code, and go
File
->Open Folder...
, and select your folderCreate a new file, with
File
->New Text File
Click
Select a language
and choosePython
Write
print("hello world")
in the file, and save it asmy_first_script.py
Press the triangular
Play
button in the top right
Now, change your script to contain the following:
print("hello world") varint = 1 print("Variable 'varint' is a", type(varint)) varstr = "astring" print("Variable 'varstr' is a", type(varstr))
Press the triangular Play
button in the top right, and you should see the following output:
hello world Variable 'varint' is a <class 'int'> Variable 'varstr' is a <class 'str'>
Can you guess what happened? Python read the file, executing each line one after the other. This is equivalent to typing the 5 lines in the REPL, except you wrote them all at once in the file. This allows you to save your program, make changes, and run it again later.
Programming in Python in practice
When programming in Python, you will find yourself working inside a text editor most of the time, building your program.
There are many different IDEs that you might want to try. There is no right or wrong IDE: you should use the one you like best. Some options are:
PyCharm (note, the Community Edition is free)