Locate your home directory and the location of Python on ...

[Pages:13]Introduction to Python

Writing and Running Programs in PyCharm, Working with Lab Files and Using Jupyter Notebook

Tools for Writing and Running programs:

? Python: this refers to the Python interpreter, the program that translates our Python code into instructions that the computer can understand

? PyCharm: a text editor for writing Python programs

? Jupyter Notebook: a tool for running short code snippets in a browser

? Lab Files: we will download and use a .zip containing files and programs for each week

As previously mentioned, we assume that you will be using the PyCharm IDE. You can use another editor/IDE, but you must be familiar with it -- or you may run into time consuming delays in learning its particular rules and quirks.

Locate your home directory and the location of Python on your system

1. First, we will find and record the path to your home directory. Your home directory is the "home base" for all the files with which you work on your computer. We will use this directory as a reference point for working with files.

a. Windows:

Open an Anaconda Prompt window:

i. In the Windows search box at the bottom of the screen, type anaconda. A results list pops up with several choices.

ii. Click on Anaconda Prompt (Anaconda3). A black box with white type appears.

iii. Look at the path starting with C:\. It usually follows this pattern:

C:\Users\username>

where username is your home directory name. This name may be your name, or it may be something related to the computer you're using like computerlab or computeruser, or it may be some other name that identifies this computer or user (the term user refers to you, the person using the computer).

iv. Copy and paste this path into a text file for later reference. It is your home directory. Keep this window open.

b. Mac:

Open a Terminal window (command prompt):

i. Click the magnifying glass (an icon at the very top row of your Mac desktop screen) and type Terminal, then press [Enter] or click on the word Terminal listed under "Top hit".

A white box with black type should appear, ending in a $ prompt and a small rectangular cursor. The prompt may be similar to this one:

Last login: Fri Sep 6 14:39:46 on ttys001 (base) username:~ username$

(Your username would stand in place of myuser above.)

ii. Click inside the Terminal window, to the right of the $. Type pwd and press [Return] (don't type the $ below):

$ pwd

After pressing [Return] you should see a line of text similar to /Users/username, where username is your username or the name of a computer user, like computerlab or computeruser.

iii. Copy and paste this path into a text file for later reference. It is your home directory. Keep this window open.

2. Next, we will find and record the path to the Python interpreter (the program that reads Python code and converts it into machine instructions). We will need to tell PyCharm about this location, so it can communicate with the Python interpreter.

a. Click back to the Terminal (on Mac) or Anaconda Prompt (on Windows), or open a new window as described in the previous step.

Click in the box at the blinking cursor, type the following command, then hit [Enter].

i. Windows:

where python

The window displays a path similar to C:\Users\username\anaconda3\python.exe, where username is the name of your computer's home directory. However, it may be different ? as long as you can see a path that has the word anaconda3 somewhere in the path, it is correct.

Note that you may also see a 2nd path to python.exe -- please focus on the anaconda3 path. If you don't see anaconda3 in this path, please contact me.

ii. Mac:

which python3

The window displays a path like /Users/username/anaconda3/bin/python3 or /Users/username/opt/anaconda3/bin/python3, or /opt/anaconda3/bin/python3, where username is the name of your computer's home directory. However, it may be different ? but as long as you can see a path that has the word anaconda somewhere in it, it is correct. If you see /usr/bin/python3, or don't see anaconda3 in a path here, please see below.

If you didn't see anaconda3 in your python path, please try typing each of the following paths at the command prompt, taking special care to spell them correctly. If one of them shows you a Python version number (3.9.1, 3.8.4, etc.) then this is the path you should record and use below.

Try each of the paths below, one at a time, replacing username with your computer's home directory name. If you see "no such file or directory", "command not found", etc, move on to the next one:

/Users/username/anaconda3/bin/python3

/Users/username/opt/anaconda3/bin/python3

/opt/anaconda3/bin/python3

If none of these paths work and you have definitely installed Anaconda and opened this Terminal window after you finished installing Anaconda, please get in touch with me right away.

b. Copy and paste the path you found above into the text file, or remember it, for later reference.

3. If you pasted the paths (home directory path and python interpreter path) into a text file, you should now have two paths recorded in the file:

a. on Windows these paths will usually be:

home directory: C:\Users\username python interpreter: C:\Users\username\anaconda3\python.exe

b. on Mac these paths will usually be similar to:

home directory: /Users/username python interpreter: /Users/username/anaconda3/python3 or

/Users/username/opt/anaconda3/bin/python3 or /opt/anaconda3/bin/python3

where username is the name of your computer's home directory. It may be helpful in future to simply remember these paths, particularly your home directory path.

Again, your python interpreter path may be different than above ? but as long as it has the word anaconda in it and is the output to where python or which python3, it is fine to use.

Launch PyCharm, create a project, write and run a Python program

4. Start a new PyCharm project. A PyCharm "project" is a folder which will serve as the home directory for files that are part of a single software project. (PyCharm also stores configuration for the project in a "hidden" folder called .idea)

a. Return to PyCharm (if it is still open from the Getting Started instructions), or Launch PyCharm, either by double-clicking the PC desktop icon, clicking the PC dock icon, or typing PyCharm into the Magnifying Glass or Windows search box and selecting PyCharm CE (Mac) or JetBrains PyCharm Community Edition (Windows).

After PyCharm launches (it will temporarily display a brightly colored banner), you should see a medium-sized box titled "Welcome to PyCharm" and the PC logo.

If you see "Tip of the Day", close this box. You can also uncheck the box that sets PyCharm to display tips of the day each time it starts.

If you see a large screen with multiple panels, you are looking at an open project. Close this project with File > Close Project. You should then see the "Welcome to PyCharm" medium-sized box.

b. Click on Create a New Project. PyCharm displays a Location blank and a Project Interpreter dropdown.

i. Look at the path to the folder that PyCharm intends to create (but do not click Create). PyCharm suggests a location in a special folder called PyCharmProjects in your home directory.

The folder is initially titled one of these:

C:\Users\username\PycharmProjects\pythonProject (Windows)

/Users/username/PycharmProjects/pythonProject (Mac)

where username is the name of your computer's home directory and pythonProject is highlighted in blue. If you prefer to choose a different location to save your projects, click the folder icon to the right of the Location blank and select a folder location. You can also type out another full path. PyCharm will keep track of this location, but you may want to note it down for future reference.

ii. Name your project session_test (but do not click Create). Change the value after the last slash to session_test, replacing pythonProject. Do not click Create yet -if you do, chose File > Close Project and start Create New Project again.

Special notes on naming your project: ? do not click Create until after you've chosen an interpreter, below -- if you do, chose File > Close Project and start Create New Project again. ? never use a space in any filename or directory name you create -- this can cause problems later on. You can use an underscore to separate words. ? please do not put a .py at the end of your project name -- this is reserved for Python files, not projects ? if you chose a different folder besides PycharmProjects you must make sure to append a new folder name (i.e. session_test) after a slash, to the end of the path. The last folder name must be new for each project.

iii. If you see the dialog titled Create Project with the message "The directory xxx is not empty" (or similar), this means that you specified a folder name that already exists. Choose a new name. (Do not click Create yet -- if you do, chose File > Close Project and start Create New Project again.)

iv. Select the Python interpreter. Now we'll tell PyCharm where to find Python, and this choice will be remembered for future projects as well.

1) Below the Location: line you see a small triangle with Python Interpreter: beside it. Click the triangle -- selections appear below.

2) Select Previously configured interpreter (the second radio button on the bottom left area of the dialog box)

3) Click the ellipsis (...) to the right of this box. Another box of the same size appears with the title Add Python interpreter.

4) On the left, click System Interpreter. To the right of this is another Interpreter: blank; you may see here or you may see a path such as /usr/bin/python.

5) Click the ellipsis (...) to the right of this box (note that this is the 2nd time we are clicking an ellipsis, in a very similar but different window). A smaller dialog with Select Python Interpreter appears, with a blank near the top and filesystem folders below.

6) In the blank you may see a path starting with C:\ or / (forward slash) highlighted in blue.

7) Go back to where you saved the path to Python in the previous step; copy this path by highlighting it and pressing Ctrl-C or Cmd-C. Make sure you are selecting the path to Python, not your home directory.

8) Return to PyCharm and click in the path blank near the top. Paste the path to python into this blank by pressing Ctrl-V or Cmd-V. The path to Python should have replaced the blue highlighted path and be in the blank by itself. If somehow the existing text got de-highlighted and is in the box alongside of the path, highlight the entire path and delete it; then paste the path to Python again.

9) Click OK: you'll be returned to the Add Python Interpreter window.

10) If you attempt to click OK but the blank becomes highlighted in red, this means that that path is invalid. Check the path, or use the file tree below to navigate to the location of python.exe or python3 (i.e., the path to python you recorded earlier).

c. Doublecheck that you have System Interpreter highlighted on the left. Make sure you have not highlighted VirtualEnv Environment. If System Interpreter is not highlighted, click on it and repeat the instructions starting at Select the Python interpreter above.

d. Click OK in the Add Python Interpreter window, then Create in the next window. PyCharm should open a larger window with a rectangular panel on the left and a larger grey space on the right. If this is your first project, PyCharm may also go through some initialization steps that take a few minutes and show some moving progress bars at the bottom of the screen -- this delay should not be repeated.

e. On Windows, if you see a message starting with Windows Defender might be... you may choose to Fix and Configure automatically, or Don't show again for this project. I am uncertain as to how either choice will impact your experience, but it does not appear to present a problem either way.

f. Check out the PyCharm project view. The left-side window is the project view -- there you can see the project folder (a little folder icon with the same name as the name you gave the project). You can use the triangle next to the project folder to view files inside the folder (after we create some). External Libraries lists any installed Python libraries you may be using in the project; this and Scratches and Consoles are not meaningful to us for this step.

g. You can open and close the project view with Alt-1 (Windows) or Cmd-1 (Mac).

h. At the very top of your window, note the location of your project folder. You can see its location, starting with C:\Users\username (Windows) or ~/ (Mac) at all times when you are working. You may need to remember this path if you want to zip up and save your working files from your learning session when working on a lab computer.

(On Mac, the tilde (~) represents your home directory, which you recorded earlier and is usually /Users/username where username is your or your computer's username.)

5. Write a new Python program. Program source code is written in "plain" (unformatted) text. We will write our source code inside PyCharm, then send the code to Python to read and run the program.

a. Locate the project folder. In the project view (the left-hand window of PyCharm), look again for the project folder icon, which looks like a file folder and has the project name (session_test).

b. Right-click the project folder icon (next to the name you gave the project) and select New > Python File (not New > File or New > New Scratch File)

c. Name your file hello.py (or whatever name you prefer, but ending in a .py extension). Make sure not to use spaces in any file or folder names! Use underscore instead.

d. Press [Enter] -- the main window becomes blank, with a small tab above it. Look to the project view on the left -- the file appears under the project folder (click the tiny triangle to show and hide it).

The file should be inside the project folder, but please double check the location of your new file -- it should be indented directly below the project folder (below and to the right of it, not aligned with it). If the file is not located there, you can select and delete it, click on the project folder, then right click and choose New > Python File again.

e. Compose your first "hello, world!" Python script by entering the following Python code in the main window:

print('hello, world!')

Retype this, but be careful to replicate the text shown here exactly.

As you type, you may notice a red squiggly line appearing below parts of your code line. This line will disappear once your syntax is correct.

f. You can save your project with Ctrl-S (Windows) or Cmd-S (Mac) -- a good habit for any file you're writing -- although PyCharm saves projects (and the files within) automatically.

g. If you see a message at the top of your program reading "No Python interpreter configured for the project", this means that PyCharm can't find Python. The needed steps are detailed above in Select Python Interpreter. You'll want to either close the project and start again with a new project, carefully following the steps in Select Python Interpreter, or you can also change the interpreter for an existing project. For an existing interpreter, click on the link in the message and then follow the directions starting with Select the Python Interpreter, above.

6. Run the Python program for the first time. Please note that you may need to wait before running a script for the first time -- see next.

a. Right click the file and select Run 'hello' (do not select Run file in Python console).

If you don't see "Run 'hello'" in the menu when you right-click the file, or this option is greyed out, PyCharm may be getting started for the first time. You'll know this is the case if you see Indexing... or Updating skeletons... noted at the bottom of the PyCharm window. Simply wait several minutes and right-click the file again -- you should

eventually see "Run 'hello'" in the menu. (Please do not select Run file in Python console.)

After clicking Run 'hello', a new tabbed window should appear at the bottom of the screen with the result of running your code. In this new Run window at the bottom of the screen, you should see hello, world! followed by the words Process finished with exit code 0. This last line (Process finished...) indicates that your Python program has finished executing successfully. If you don't see this line, it means that your program has not yet finished executing.

b. If you see Traceback: or File [filename] along with 4 or so lines of output (some of this text may be colored red) with the word SyntaxError, IndentationError or NameError, you've made your first error. Congrats! This is the first of many. :) Go back to your script and compare your text character-by-character with the program text: print('hello, world!'). It must match this program character-by-character to be correctly interpreted by Python. If you replicate this code source exactly, you should not see an error. If you see an error that you can't account for and prevents you from running your script, please contact me.

c. Again, please note that when PyCharm is used for the first time, it is sometimes slow to create projects or run programs (if this is the case you'll see a progress bar with Indexing... or Updating.... This delay should not occur after the first few runs of a program or creation of a project.

7. Edit, re-run, edit, re-run... Here's a tip: it can be very helpful to develop a keyboard-based workflow that will allow you to run through the development cycle repeatedly, without having to move to the mouse or trackpad, as shifting your hands between mouse and keyboard repeatedly is unnecessary effort.

a. Click in the edit window (the window with the code in it) and make an edit to your script (change world! to weird!).

b. Use a keyboard shortcut to execute the script again: Shift-F10 (Windows) or Ctrl-R (Mac). Note the change in output in the Run window.

c. Continue making edits to the script. When done, use Shift-F10 or Ctrl-R to run the script again.

d. Attempt to make each "round trip" without moving your hand to the mouse. You'll save hours of this movement in the long run!

8. Running a new second script. Keep in mind that when creating and running a new script, the shortcut Shift-F10 or Ctrl-R will only run the last-run script. To run a new script for the first time, right click the main window and select Run 'newscript' (where newscript is the name of your new script). After that, Shift-F10 or Ctrl-R can run this new script again -- this command always re-runs the last script you ran.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download