*.py
extensionYou know a file is a Python program when it ends with a .py
extension.
Just like with formatting, Python’s PEP8 guidelines give us a few helpful tips about how to name our Python program files.
âšī¸ In Python:
_
â Some good example filenames:
apis.py
exceptions.py
personal_blog.py
âī¸ Some bad example filenames:
MYFILE.PY
CamelCaseFile.py
really_long_over_descriptive_project_file_name.py
*.pyc
files?For optimization and other reasons, Python code can be compiled to intermediary .pyc
files. The good news is you don’t have to worry about them. The bad news is, very occasionally stale versions of these compiled files can cause problems. To safely delete them from the current project directory, run find . -name "*.pyc" -delete
(on linux or macOS).
git
tip: use a .gitignore
for PythonIf you use git
for source control, you’ll want to make sure that these compiled *.pyc
files are ignored, and not added to your repository.
The best way to do this is to add the standard .gitignore
file for Python to your project.
Running Python files from VS Code is really quick and easy.
To create a new file in VS Code, hit Ctrl+N
on Windows and Linux, and âN
(command + N) on Mac OS.
This will open a new file. Next, save the file with a .py
extension.
Create a new simple Python program in a file called hello.py
in our pyworkshop
direc tory with the following contents:
# in file: hello.py
greetings = ["Hello", "Bonjour", "Hola"]
for greeting in greetings:
print(f"{greeting}, World!")
Next, you’ll need to open your terminal if you don’t have it open already. The quick keyboard shortcut to do that is Ctrl - `
If you already had your Python REPL open, you’ll need to select a terminal with a shell in it (generally, the one labeled with 1:
).
Once you’ve opened your hello.py
file and selected your new terminal window, open the VS Code command palette.
Open the command palette with Ctrl+Shift+P
on Windows and Linux, and ââ§P
(command + shift + P) on Mac OS.
Select Python: Run Python File in Terminal
You should see:
Hello, World!
Bonjour, World!
Hola, World!
How easy was that? đ
If you want to run a Python file without using the command palette, just open your terminal of choice, cd
into the directory with your code, and type in the command python
followed by a space, and the name of your Python program.
(env) $ python hello.py
Hello, World!
Bonjour, World!
Hola, World!
This also works in the VS Code terminal.