In today's lab, you've seen how to run python from the command line (also known as a shell) via the interpreter; however, we can also write our code in a separate text file, which we can save and then run from the command line. This is how most people create python programs. However, before we can start writing more Python, you'll need to learn a few shell commands.
As you probably already know, your python files, and any file for that matter, can be found within a particular folder (also know as a directory) on your computer in a structure similar to the one shown below:
To navigate to a particular python file we will need to make use of the following shell commands (whenever we say "enter a command" this means type the command and then press enter to execute it):
First, enter the command ls
to view a list of all of the files and directories that are located in your current directory (if you're using windows the command is dir
not ls
). If you see a ~
next to your user name (alonzo
is the username below) then we are in our home directory. To go directly to your home directory enter the command cd
. When your enter ls
in your home directory you should see something similar to the following:
Alonzos-MacBook:~ alonzo$ ls
Applications Downloads Pictures
Library Public Music
Desktop Movies Documents
Next, move into the Documents directory by entering the command cd Documents
. This stands for change directory to the given directory name. The following should appear (notice that the ~
has now been replaced by the directory name Documents
):
Alonzos-MacBook:~ alonzo$ cd Documents
Alonzos-MacBook:Documents alonzo$
If we need to move back out of our directory we can enter the command cd ..
Shown below is how to move out of our documents directory and then back into it:
Alonzos-MacBook:Documents alonzo$ cd ..
Alonzos-MacBook:~ alonzo$ cd Documents
Alonzos-MacBook:Documents alonzo$
Finally, let's make a directory that will hold our python files.We can enter the command mkdir PythonLab1
to create a directory called PythonLab1 as shown below. Now that we have made this new directory enter the command cd PythonLab1
to go to the directory.
Alonzos-MacBook:Documents alonzo$
Alonzos-MacBook:Documents alonzo$ mkdir PythonLab1
Alonzos-MacBook:Documents alonzo$ cd PythonLab1
Alonzos-MacBook:PythonLab1 alonzo$
Now we have a place to put all of our python files! Continue to the next page to download the starter file for this lab.