Write Python in Script Files
In this module, we will learn:
- to write a Python script in our text editor and run it in the Terminal
- how programming languages relate to our machines and to the available libraries
In this module, we will look at how to save our Python scripts in a text file. While the Interactive Interpreter is really useful for figuring things out, files are easier to share and enable us to keep our save our work as we go.
1. Writing and Executing Script Files
First, exit out of the Python Interactive Interpreter by running exit().
You should still be in the folder we made at the beginning of the day. Check using pwd.
Now remember we created a file called "my_first_script.py"? Let's open that file again and remind ourselves of what we wrote.
and on Windows:
Start Notepad++ my_first_script.py
It should say 'print "Hello World"'. Now that you know something about Python functions, what do you expect this script to do?
Let's test it out! To execute a Python file, run the following in Terminal:
Your Terminal window should look something like:
1 2 3
jeriwieringa$ python my_first_script.py Hello World jeriwieringa$
Congratulations! You just executed your first Python script!
Writing our DPyLA Script
Now let's recreate some of the work we did in the Interactive Interpreter in this script file.
Delete print "Hello World" so that you're working with a clean file.
First, at the beginning of a Python file you need to list the libraries that we will be using. The computer will execute the code in the order it reads it, so it is important that your commands follow a logical structure down the page.
from dpla.api import DPLA
Then we need to store our API key:
dpla = DPLA('YourAPIKey')
Then we can write our search query:
result = dpla.search('cooking')
Your file should look like this:
1 2 3 4
from dpla.ap import DPLA dpla = DPLA('YourAPIKey') result = dpla.search('cooking')
Save the file and go back to Terminal. Run:
You should notice that your computer works awhile and then returns to normal, but doesn't tell you anything about what it did. To see results, we can use the print function again.
Open your script file again (open my_first_script.pyor Start notepad++ my_first_script.py).
Print is a very useful tool for checking on your script as it moves through your commands. You can use "print" to make sure your query is returning what you wanted, that your code is parsing as you expect, and to identify where things go wrong.
Work with your group to add another line to the file that uses the "print" function to display one item from your search.
Work with your table to add comments to the lines in 'my_first_script.py'
2. Programming Languages
It is time to return to the pen and paper! Work with your group and your coach to talk about Python as a programming language and how it fits in the ecosystem of your computer.
*Python 3 does require the use of () for print, making it more consistent with the Python syntax for functions.