Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. Creating and Running .py Files

Creating and Running .py Files

This page explains how to save Python code as a text file and run it. The file itself is simply a plain text file saved with a .py extension.

How to write a .py file

Write your Python code in a text editor and save the file with a .py extension. Save the file using the UTF-8 character encoding.

sample_hello.py
name = 'Okabe Rintaro'
age = 18

print('Name:', name)
print('Age:', age)

if age >= 20:
    print('Adult.')
else:
    print('Minor.')

Write Python code directly in the text file and save it like this. Use 4 spaces (or tabs, as long as they are consistent) for indentation.

How to write comments

You can write comments (notes) in a .py file. Comments are ignored by the Python interpreter, so they are useful for leaving descriptions or notes about the code.

SyntaxDescription
# commentA single-line comment. Write it with one space after #. Everything from # to the end of the line is a comment.
"""comment"""A multi-line comment (docstring). Everything from """ to """ is a comment.
'''comment'''A multi-line comment (docstring). Everything from ''' to ''' is a comment.
# A script that displays user information.

def greet(name, age):
    '''A function that receives a name and age and displays a greeting.'''
    print('Name:', name)
    print('Age:', age)

greet('Makise Kurisu', 18)

A string enclosed in """ or ''' written immediately below a function is called a docstring and is used as a description of the function. The # symbol is widely used for inline code comments.

How to run

Open a terminal (macOS / Linux) or command prompt (Windows), navigate to the directory where the .py file is saved, then run it.

Run on macOS / Linux

Use the python3 command on macOS and Linux.

python3 hello.py
Name: Okabe Rintaro
Age: 18
Minor.

Run on Windows

Use the python command on Windows.

python hello.py
Name: Okabe Rintaro
Age: 18
Minor.

If Python is not installed, see Setup.

Summary

A .py file is simply a plain text file. You can create one by writing Python code in a text editor and saving it with a .py extension. No special tools are needed.

Saving the code to a file means you can run the same code any number of times. It also makes it easier to manage longer code.

Use python3 on macOS / Linux and python on Windows. Depending on the environment, both commands may work.

For recommended editors and Python installation instructions, see Setup.

If you find any errors or copyright issues, please .