Running your first Python program from start to finish takes four steps: put the file where the terminal can find it, call the right interpreter, read what comes back, and know what to do when something breaks. Most beginners get through the first two within a minute and then stop at the third and the fourth. This lesson walks through the whole loop, including the parts that nobody mentions until the day you need them.
The previous lesson in this module covered "Installing Python 3.12 on Windows, macOS and Linux", and the next lesson in this module is about "print(), input() and Your First Variables".
How do you run a Python file?
Save your code in a file with a .py extension, and then give that file to the interpreter from a terminal. On Windows and Linux the command is python your_file.py. On macOS and Linux, python3 your_file.py is the safer spelling, because python may point at the Xcode tools or may not exist at all.
Three details cause most of the early problems.
- Your terminal may not be in the folder that holds your file. The terminal often starts in your home folder, and relative paths are measured from wherever the terminal is sitting. If you see "No such file or directory", print the location with
python -c "import os; print(os.getcwd())"and move to the folder that really holds the file. - The file name becomes part of your command. A file called
my script.pyneeds quotes around it, and a script namedtest.pycan clash with other tools that use the same name. - Two spellings can mean two different results. Running
pythonand runningpython3may use different versions with different packages installed. Pick one spelling and stay with it.
Two shortcuts are worth knowing from the start. The command python -c "print(2 ** 10)" runs one line of code without creating a file, which is handy for checking a value or a flag. And python -m module_name runs a module like a script, which is how you start a package that ships with a __main__ entry point.
Editors do exactly the same thing behind a button. A "run" command in an editor is really a terminal command that starts the interpreter with your file, so you get the same result either way. The difference is that the editor opens the terminal for you and lets you step through the code one line at a time. When a program fails, looking at its state at the exact moment it failed is often faster than adding print statements and running it again.
What does a Python program look like from top to bottom?
A script that you plan to reuse has a shape that is worth copying. Put the imports at the top, the constants next, then functions that each do one job, and finish with a single entry point at the bottom. That entry point sits behind a condition that looks strange the first time you meet it.
"""A small report program you can also import from other scripts."""
from datetime import date
APP_NAME = 'daily report'
def build_rows(records):
"""Turn a list of dictionaries into printable lines."""
lines = []
for item in records:
lines.append(f"{item['name']}: {item['count']}")
return lines
def render(records, today=None):
"""Build the whole report as one string."""
today = today or date.today()
lines = [APP_NAME + ' - ' + today.isoformat()]
lines.extend(build_rows(records))
total = 0
for item in records:
total = total + item['count']
lines.append('total: ' + str(total))
return '\n'.join(lines)
def main():
records = [{'name': 'apples', 'count': 12}, {'name': 'pears', 'count': 7}]
print(render(records))
if __name__ == '__main__':
main()
When you run this file directly, Python sets the module's __name__ to '__main__', so the guard passes and main() runs. When another file does import report, the same file runs again, but __name__ is now 'report', the guard fails, and nothing happens except that the definitions are created. That one line lets other scripts import your work without running it by accident.
Two more built-in names are useful here. __file__ holds the path of the script that is running, which helps you find files that sit next to it. And sys.argv holds the command-line arguments, where the first entry is the script name and the rest is whatever the user typed.
import sys
# sys.argv[0] is the script path. Everything after it is user input.
arguments = sys.argv[1:]
name = arguments[0] if arguments else 'world'
print('hello, ' + name + '!')
print('raw argv was:', sys.argv)
Run that with no arguments and it greets the world. Run it as python greet.py Ada and it greets Ada instead. Notice that the script did not crash when the argument was missing, because it checked the list before it read from it.
How do you make sense of a Python traceback?
When a program fails, Python prints a traceback. It is a list of frames, and each frame shows the file, the line number, the source line, and the expression that failed. Beginners read it from the top and get lost in the first frame, which is usually library code that nobody needs to change. Read it from the bottom instead. The very last line gives you the exception type and its message, and the line just above it points at the exact expression that raised it.
import traceback
def divide(numerator, denominator):
return numerator / denominator
try:
divide(10, 0)
except ZeroDivisionError:
# format_exc() gives the same report an uncaught error would print.
report = traceback.format_exc()
print('caught it. the traceback looked like this:')
print(report.rstrip())
The report ends with ZeroDivisionError: division by zero, and the frame right above it shows the line that caused the problem. Once you get used to reading bottom-up, a traceback becomes a short map instead of a wall of text.
Three error types are worth recognising straight away. NameError means you used a name that does not exist here, which is usually a typo or a missing import. TypeError means the types do not work together, such as adding a string to a number. IndentationError means the block structure is wrong, and it is a very common first-week error, because one stray space changes what Python thinks the block is.
One more type is worth keeping separate from the rest. AssertionError comes from a failed assert statement, which you write yourself to state something that should always be true. Seeing one means the program caught itself breaking its own rule, which is a very different situation from an unexpected crash.
What do exit codes mean, and why should you care?
A process that finishes successfully exits with status 0. Any other status means that something went wrong, and the exact number is a choice that you make. Shell scripts, task schedulers, and CI pipelines decide whether a job succeeded by reading that number and not by reading the output text. If your script prints an error and then exits with 0, every automated system around it believes that the job worked.
import sys
def main():
print('doing the work...')
# A real program would call sys.exit(1) here when something failed.
return 0
status = main()
print('this process will exit with status:', status)
sys.exit(status)
Calling sys.exit(1) ends the program at once with a failure status. Calling sys.exit('could not open file') prints that message to the error stream and exits with status 1, which is an easy way to fail and explain why at the same time.
Your turn: run it, break it, then fix it
- Create a folder called
python-laband put the first program from this page inside it asreport.py. Open a terminal in that folder, runpython report.py, and check that the report prints. - From the same folder, run
python -c "import os; print(os.getcwd())"to show where the terminal is sitting. - Now break it on purpose. Change
item['count']toitem['counts']insidebuild_rows. Run the script again and read the traceback from the bottom line upwards. Say the error type and the wrong expression out loud. - Fix the typo. Then divide by zero on purpose in a new line and read the new traceback. Notice that the order of the frames did not change.
- Finally, import your script from a second file with
import reportand callreport.render([{'name': 'test', 'count': 1}]). It must print the report without running the whole script, which proves that the__main__guard is working.
Key takeaways
- Run a file with
python your_file.pyfrom the folder that contains it, and checkos.getcwd()when the file "does not exist". - Guard the entry point with
if __name__ == '__main__':so that your script stays importable. - Read a traceback from the bottom. The last line is the error type and message, and the line above it is the cause.
- Exit status 0 means success, anything else means failure, and automation trusts that number.
sys.argvholds your command-line arguments, with the script path in position zero.