Introduction to Python Writing and Running Programs Working with Lab Files These instructions take you through the steps of writing and running your first program, as well as using the lab files in our PyCharm projects each week. Each week we will work with a different folder, containing files needed for in-class exercises and homework for that week. As previously, we presume that you will be using the PyCharm IDE. You can use another Editor/IDE -- but you must be very familiar with it, or you may encounter confusion in learning its special rules and quirks. Writing and Running Programs 1. Start a new PyCharm project. A PyCharm project is contained within a folder. When we create a new project, PyCharm will show us the full path to where this folder will be created (for now, do not choose an existing folder). The name we give our project will also be the name of the folder (our first project will be called session_01). Make sure not to put a.py at the end of your project name. Also: spaces in names are a no-no! a. If it is not already running, launch PyCharm. You should see a small box titled "Welcome to PyCharm Community Edition". If instead you see a large screen with multiple panels, you are looking at an open project. Close this project with File > Close Project. b. Click on Create a New Project (we will start with a project called session_01). PyCharm displays a Location blank and a Project Interpreter dropdown (with a valid interpreter usually selected -- see below). i. Look at the path to the folder that PyCharm intends to create. PyCharm suggests a location in a special folder called PyCharmProjects in your home directory. (This folder will read as /Users/username/PyCharmProjects/untitled (on Mac) or C:\Users\username\PyCharmProjects\untitled (on Windows). You can use this location, or if you prefer choose a different one, click the ellipsis ( ) 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. After deciding on the default, or after selecting a new location, name your project session_01: change the value after the last slash from untitled to session_01. A session_01/ folder will be created there. Please do not put a.py at the end of your project name -- this is reserved for Python files, not folders or projects. Also, never use a space in any filename or directory name you create -- it can cause problems for developers at the command line. iii. If you see the warning "Environment location directory is not empty" (or similar), this means that you didn't specify a new folder name. To open an existing folder, hit
Cancel and choose Open or select the folder from the shortcut list on the left of the welcome window. If you wish to overwrite an existing project, you'll need to find the folder at its location in the filesystem and delete it from there. Open the project, right-click the folder, choose "Show in Finder" or "Show in Explorer" and a Finder or Explorer window will open showing the folder. Leave this window open and go back to PyCharm, close the project with File > Close, then return to the Finder or Explorer window and delete the folder. You can then open a new project by this name. Note on Project Interpreter: New Virtualenv Environment: this dropdown shows the version of Python we'll be using ("Base interpreter") as well as the location of the venv configuration folder. This is handled automatically by PyCharm. If PyCharm cannot find your version of Python or if it is using an invalid path, you may see an error here. You should of course confirm that you have Python installed on your system. You can then use the "elipsis" ( ) button to attempt to navigate to your version of Python. It may be located at /usr/bin/python3 or /usr/bin/python3.7 (Mac) or C:\Users\myuser\AppData\Local\Programs\Python\Python37-32\python.exe or similar (Windows). It may be located elsewhere. See me for assistance. c. Click Create. PyCharm should open a larger window with a rectangular panel on the left. It may take several seconds to prepare the environment. If this is your first project, PyCharm may also go through some initialization steps that take a few minutes -- this delay should not be repeated. d. The left-side window is the project view -- there you can see the project folder (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. If this is a new project, the project folder (with the name you gave the project) will contain a venv folder and nothing else. 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. e. You can open and close the project view with Cmd-1 or Alt-1. 2. Write a new Python program. Program source code is written in "plain" (unformatted) text. We will write this text file inside PyCharm, then ask Python to read and run the program. a. In the project view, right-click the project folder (the folder with the name you gave the project) and select New > Python File (not New > File) b. Name your file hello.py (or whatever name you prefer, ending in a.py extension). c. Click OK -- the file appears under the project folder in the project view (click the tiny triangle to see it), and also appears as a tab in the main window. The file should be inside the project folder, but double check the location of your new file - - it should be indented under the project folder directly underneath the venv folder (it should not be indented further to the right (and thus inside) the venv folder). If the file is
inside venv, you can cut it (Ctrl-C/Cmd-C), click on the project folder and then paste it (Ctrl-V/Cmd-V); or you can delete it, click on the project folder, and choose File > New again. d. Create your first "hello, world!" app by entering the following Python code: print('hello, world!') e. You can save your script with Cmd-S (Mac) or Ctrl-S (Windows) -- a good habit for any file you're writing -- although it appears that you do not need to do so, because PyCharm saves projects (and the files within) automatically. f. 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. i. click the link ii. click the Python Interpreter dropdown. You should see a list of paths to python; make sure to ignore the paths with venv in them iii. find a path to python or python.exe and select it iv. if you don't see a valid python path, click Show All and see if it can be found in that list v. if still not found, you can then use the "elipsis" ( ) button to attempt to navigate to your version of Python. It may be located at /usr/bin/python3 or /usr/bin/python3.7 (Mac) or C:\Users\myuser\AppData\Local\Programs\Python\Python37-32\python.exe or similar (Windows). It may be located elsewhere. See me for assistance vi. if you found a valid path to python, select it, then click Apply and OK vii. please note that the "No Python interpreter" message may linger for a few minutes after a valid interpreter is selected and applied 3. Run the Python program. I recommend that you run your programs in a Terminal / Command Prompt window in PyCharm (rather than the Run window). In the Terminal window you are asking the operating system to run your code directly; with Run, PyCharm acts as an intermediary. As mentioned above, if you use the Run command to run your programs, you will need to do something differently when we start working with command line arguments in Session 3. I recommend using Terminal as described below. a. To open the Terminal window, you can hit Cmd-T or Alt-T -- a horizontal rectangular panel appears at the bottom, with a Command Prompt for your operating system (note that it is the same prompt we used to test the python version with python -V). You can also open this window by clicking on Terminal at the bottom of the PyCharm window. b. Drag the top of the rectangular panel upward so it is larger. As you work, you will be switching back and forth between the edit window and the Terminal window. I prefer a large Terminal window, and I pop back and forth between windows. We will demonstrate this in class.
c. At the Terminal prompt in the lower window, type one of the following, depending on how you invoked Python in the steps above: python hello.py python3 hello.py py hello.py Here we are starting Python, and giving Python the name of the script to read and execute. After hitting [Enter] you should see the output of the program, which is the printed greeting. If you see python is not an internal or external command or python: file not found or a simiar message, but you were able to see the version of Python in the Getting Started instructions, go back and recall how you successfully launched Python previously. Remember that if you used python3 for your initial test of python, you'll be using python3 hello.py. This is important because the 2.7 version of python is similar but not the same as the 3.7 (or 3.x number) version and It can be difficult to see the difference. If you see can't open file 'myfile' where myfile is the new file you created, your Terminal may be focused in the wrong directory -- use the red X on the left side of the Terminal window to close the Terminal window, then click the Terminal tab to reopen it. d. To generate clear output with each new run of the program (sometimes vital to smooth progress and understanding) issue a 'clear' command before the python command: i. Mac OS: clear; python hello.py ii. Windows: cls & python hello.py This merely clears the screen before showing the script output. You should see the output of the script clearly displayed by itself at the top of the page. Keep in mind that if you scroll up on this window you'll see output from prior runs of the program. 4. Double-check the Python version. Some students get this far without realizing that they are using Python 2.7 (or other 2.x number) instead of the 3.6 (or other 3.x number) version. Rewrite your code so it looks like this: import sys print('hello,' + sys.version) You should see hello, 3.7.0 (v3.7.0:5fd3. or another number after 'hello, ' that starts with 3. If you are seeing a number that starts with 2 instead, you either need to remember to use python3 when you are running the program in the Terminal or Command Prompt window, or we need to adjust your computer's PATH variable to point to python 3 -- please get in touch with me if you think you are using version 2.
5. Edit, switch, re-run, switch, edit Here's a helpful 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 hit one more key than necessary. a. Click in the edit window and make an edit to your script (change world! to weird!) b. Use Cmd-T (Mac) or Alt-T (Windows) to open the Terminal window c. Command History: move this file in a location where you can retrieve it later in case you want to restore PyCharm settings defaults. Hit the Up Arrow to bring up your last command, then hit Enter. The program will run again and you'll see your program output. This can be a tremendously helpful way to avoid excess typing. d. Use Cmd-T (Mac) or Alt-T (Windows) to close the Terminal window. Window focus should return to the edit window. e. Make an edit to your script (change weird! to python!!!) f. Use Cmd-T or Alt-T to open the Terminal window g. Hit the Up Arrow to bring up your last command, then hit Enter. View the changed result. h. Use Cmd-T or Alt-T to close the Terminal window. Window focus should return to the edit window. i. Lather, rinse, repeat! Using Each Week's Lab Files 1. Load this week's lab files into your project. Each week I will provide a.zip file with a folder containing files needed for in-class work, for homework, and for homework testing. Usually, this file will be provided a full week ahead of class. Before class, or at the start of class, please create a working project for the week, unzip the week's zip file and copy these files to the week's project folder. a. Visit the source data link on the class website: http://davidbpython.com/introductory_python/python_data b. Click on the.zip for the current week (start with session_01_objects_types.zip). The file should download. c. Find the file and double-click it. i. On the Mac, a new folder will appear next to the zip file. Double-click this folder to reveal the files.
ii. On the PC, the zip file will open as if it were a Windows Explorer winodow, showing all of the files. However, this is not an open folder. 1) Click on Extract all near the top of the window. A dialog showing the full path to the new folder will appear. 2) Click Extract. A new window with a folder with the same name will appear (you may also see a MACOSX folder; you may disregard). 3) Double-click the session folder to reveal the files. Keep this window open. d. Launch or return to PyCharm. We will be moving the session files to the project for that session. e. If a different project is open, close the project with File > Close. Create a new project with the session name (session_01, etc.) or reopen one you have already created. f. In the Finder or Explorer window where you see the session files, select all of the files and copy them: hit Ctrl-C or right click and select Copy. g. In PyCharm, click the session folder and hit Ctrl-V, or right click and select Paste. PyCharm will ask whether you would like to copy the files to the project; click Yes. h. Once copied, you should see all the files from the.zip file in your project. You now have what you need to follow along in class as well as do exercises and homework. i. Please make sure that you have pasted the files, not the folder of files, into your project folder. You should see each file indented under the session folder, at the same level as the venv folder. 2. Run one of the project files. a. In PyCharm, open the Terminal window using Cmd/Alt-T, or by clicking the Terminal tab at the bottom of the PyCharm window. b. At the prompt, type one of the following, depending on how you invoked Python in the past: python 00_hello.py python3 00_hello.py py 00_hello.py
3. Use [Tab] completion to save typing and reduce errors. You don't need to type out the full name of the file you want to run -- you can just type the start of the filename, then hit [Tab] to complete. a. At the Terminal prompt, type python, python3 or py depending on how you invoked Python in the past. b. Start to type the name of the file you want to run, for example 00 c. Instead of typing out the whole filename, hit [Tab]. If your Terminal window is in the same directory as the file, and if what you type is unique to any filenames in this directory, you should see the rest of the filename completed for you. Hit [Enter] to execute the command. 4. Use "up arrow" to save typing when re-running a program. The next time you want to run the same command as previous (i.e., when re-running a Python program after changing it), instead of typing anything, hit "up arrow" on your keyboard. You will see the same command repeated. Hit [Enter] to execute the command. 5. Take the lab files home if desired. During class, we will make changes to the lab scripts. You can of course take notes or do your own experiments using these scripts, and you can create new ones. Since they cover the features we'll need for the homework, they will hopefully be helpful to you when you are doing the assignments. a. At the end of class you may zip up the project folder and email it to yourself, or save it on the lab's shared drive. i. To zip up the project folder to send by email, find the lab folder on your Desktop or elsewhere, right click the folder and select Compress (Mac) or Send to > Compressed (zip) folder (Windows). A new.zip file should be created (you may need to rename it or save it in a different location in order avoid conflict with the original.zip file. Or, you can always delete or overwrite the original. ii. Some email clients will refuse to send a file with a.zip extension. You can get around this by changing the extension (to anything, even.txt). After retrieving the file from email, you can change the extension back to.zip before opening it. iii. To reach the lab computer's share drive, look for the link to the share drive on the Desktop. Inside that folder you should see a "Student Folder" or similarly named folder indicating this is for student work. Enter that folder, then (if this is your first time here) create a new folder named after yourself. Although this drive is shared, no one will likely tamper with it or even read it. (However, it will be visible.) If you see any errors, anomalies, or if anything seems confusing in these instructions, please let me know as soon as possible. You'll be helping others if you do (or allowing others to be confused if you don't!). Congratulations!