Running Python
Basics6 min readLesson 1 of 8
Python reads your instructions and carries them out. You can use it in two ways: type one line at a time in the interactive shell, or save several lines in a file and run the whole script. The shell is quick for small tests, and a file keeps work that you want to run again.
# Save this as hello.py
print('Hello, world!')
print('This file runs from top to bottom.')1.1 The shell
To open the shell, type python in a terminal, or py on Windows installations that provide it. The >>> prompt means Python is waiting for one statement. Type exit() to leave.
1.2 Running a saved file
- Open a terminal in the folder that holds the file.
- Type
python hello.py. - Press Enter and read the output from top to bottom.
Python reads the file from the first line to the last and stops if a line fails.
total = 7 + 5
print('The total is', total)
print('The program has finished.')1.3 When the file will not run
A common mix-up is running a file from the wrong folder. python hello.py looks for hello.py in the folder where the terminal is open, so a FileNotFoundError usually means one of these:
- the path is wrong
- the file was saved under another name
- the terminal is open in a different folder
Check the folder in your file browser and run the command from there. Saving the file with a .py extension also helps the editor and the terminal treat it as Python source.
# Text keeps its quote marks off the screen.
print('2 + 2')
print(2 + 2)1.4 Practice
- Create a file named
first.pywith twoprintcalls, then run it. - Change one message and run the file again.
- Type a single expression after the
>>>prompt in the shell and press Enter.
If the terminal cannot find the file, check the folder before you touch the code.
