Learning Objectives
- Be able to create a Python source file from scratch.
- Be able to run your Python source file and provide inputs and see outputs.
- Understand what an interpreter, editor, and IDE are used for.
Contents
- Video
- Python Source Files
- Working with Python
- Components of a Python File
- Editors and Development Programs
Video
Python Source Files
Python uses a file extension .py (python). This identifies a file as a Python source file. We can create a new .py file by using any text editor, or IDE. Throughout this tutorial, I will be using Visual Studio Code, which can be freely downloaded for most operating systems at: https://code.visualstudio.com/. For absolute beginners and for those in the data or visual sciences, I recommend the Spyder IDE, which is available with the Anaconda package here: https://www.anaconda.com/products/individual.
When you click “New File”, you can create a new Python file. At first, this will create something, such as Untitled-1. When your first save the file, it will bring up the file explorer on either a Mac or PC. From here, you will get to decide where to put your file. Remember this location! When you go to submit assignments, you will need to know this location.
Notice the “Save as type” near the bottom of the screen. When you click this, you will see a laundry list of file types. The one you’re looking for is Python.
You will now be able to write Python code. The editor will automatically change colors on special keywords or strings or constructs in Python. This is called syntax highlighting and it helps you to immediately distinguish among different Python pieces, such as a statement, variable, function, and so forth.
We can now use Visual Studio Code to run the Python file. If pieces of the Python runtime is not available, Visual Studio Code will ask you on the bottom right if you want to install these components. If you do not install them, you might have trouble running a Python file.
If you click the arrow with a bug next to it, it will bring up the Run and Debug menu. Press the big blue Run and Debug to start running your program. VS Code will then ask you what type of debug configuration you want to run, select Python File.
VS Code will then bring up the debugging console and start running your program. You can interact with your program here. For instance, I need to enter the numerator and denominator. So, when prompted, I keyed in 7.5 for the numerator and 10.2 for the denominator.
If you have a Mac or another operating system other than Windows, this console will look a little bit different. However, the essentials are the same.
Working with Python
Now, we can set up the build environment so we can run our Python files, but what about actually writing Python? When we begin, it’s nice to know what we want to accomplish. One good way to learn is to see what an already existing program does, and then pick it apart to see what each component of that program does. Let’s take our example program we wrote above and see what it does. There are more advanced concepts being used in it than you probably have seen before, but we can at least describe each component.
def main(): numerator = float(input("Enter the numerator: ")) denominator = float(input("Enter the denominator: ")) result = numerator / denominator print("Result is", result) if __name__ == '__main__': main()
Recall that we can add comments using the pound sign ‘#’. Also notice that the flow of the program is: input, process, output. Keep this flow in mind. We need certain data from the user (input). We need to do some sort of calculation with this data (process). We need to give the result to the user (output).
def main(): # We are programming a fraction calculator, so we ask the user # for both the numerator and denominator. I'm converting them # into a 'float', which means that the value returned can store a # decimal. numerator = float(input("Enter the numerator: ")) denominator = float(input("Enter the denominator: ")) # Our result is simply the numerator over the denominator. In this # case, we will also get a float (decimal) value back. result = numerator / denominator print("Result is", result) # main is a function, which we can tell by the 'def' in front of it above. # This means 'define' a function. However, to actually get this function to # run, we 'call' it as shown below by name followed by open and closed # parentheses. # We use the if __name__ to make sure we're running as a Python source # file. Since any source file can be imported as a module, it is important # to always invoke your program with this if statement. if __name__ == '__main__': main()
Components of a Python File
You see we created a variable using the equals sign ‘=’. In Python this is called the assignment operator. We assign the right hand side to the left hand side. For example i = 100
will assign the value 100 into a variable called i. If the variable already exists, the original variable will be overwritten! See if you can figure out what is printed to the screen below.
def main(): i = 100 + 20 i = i + 75 print("The value of i is", i) if __name__ == '__main__': main()
We can see with i = 100 + 20, that we will add 100 and 20 to get 120. This will then be assigned into i. For the second line, i = i + 75, the original value of i will be added to 75, so 120 + 75 is 195. We then print this value.
The flow of a Python file is from top to bottom, meaning the Python interpreter will start reading your code at the top line of your file and work its way down. However, because we are putting our code under def main(), it doesn’t execute until we call main, which is done with the last two lines of the program (if __name__ followed by main()). Python allows our code to be imported (you will do this later with packages and libraries) or to be ran as a standalone program. Python also keeps track of how it is being invoked. If it is being invoked as a standalone program, it will set __name__ equal to “__main__”. Yes, a bit esoteric, but that’s how Python chose to do it. If we import your code as a module the __name__ will no be main, and your code won’t run until what we imported is invoked manually.
The subsequent chapters will discuss the elements of a Python file. You will hear terms like, keyword, expression, statement, and so forth. In time, you will come to know what these mean.
Editors
There has to be a way to actually write the Python code itself. This is done through a program called an editor. This editor is any text editor that you want to use. Some editors are geared specifically for Python, such as IDLE (IDLE — Python 3.9.1 documentation), which is included with Python.
For scientists and engineers, your company or school or department will use what they think is appropriate to edit Python files.
To make things easier, many programmers have designed different editors geared towards one thing or another. Think of this like looking at a car sales lot. The car’s job is to transport you. The editor’s job is just to write Python code. However, you can get nice features, such as syntax highlighting and code completion. All in all, the goal is to write Python, but whether you drive in style or not depends on which editor you choose.
Interpreter
When we write Python, we are writing a human-readable text file. However, this in of itself does not instruct the computer to do anything. Much like me just writing this doesn’t do anything until someone comes along reads it and understands it.
The interpreter’s job is to read your text file and make it do something on the computer. The language that the interpreter reads in this case is Python. Python is just a set of rules, much like how English has rules so we can understand one another.
Packages (aka Libraries)
As you can see, we have the editor to write Python and the interpreter to read Python. However, if we had to write over and over again how useful utilities worked in Python every time we made a new program, we wouldn’t get much done.
This is where packages (known as libraries) come into play. A library is a set of Python code. You will be creating your own libraries so that you can share code.
For example, I can write a module, which is just a Python file, and import the code that I wrote into any other program I want. Take the example files below:
def do_something(): print("Yay, you're using my library!")
Then, we can import this code into our code by using its name (before the .py part). For example, if I named the file above something.py, I can import it as follows:
import something something.do_something()
With the dumb program I just made above, I never have to write how to print “Yay, you’re using my library again!” This is helpful when you have code that you use over and over again.
Package Manager
There are many different libraries/packages/modules (all essentially mean the same thing) that have been distributed for wide use. For example, we will be using numpy, matplotlib, scipy, and requests. These are all libraries that some programmer wrote to make our lives easier. However, getting these libraries used to be hard. We would have to go to a specific website, download the package, and run its installer.
To make life even easier, programmers have created package managers. The one I have you use in this course is called pip which stands for Package Installer for Python. Now, all I have to do is to tell pip that I want requests, and it will download it, install it, and do anything else needed so I can use it!
Integrated Development Environment
There are essentially three things we are doing: downloading/installing packages, editing Python programs, and running Python programs (interpreting). These are usually performed by a package manager program, an editor program, and an interpreter program. This gets out of hand quickly. So, to make life easy(TM), programmers have created a single programs called Integrated Development Environments or IDEs for short. These integrate the editor, package manager, and interpreter all-in-one.
For example, VS Code is an IDE. It contains an editor, package manager, and interpreter. In your major program, you will probably be asked to use one or more IDEs. Generally what happens is a professor or company gets used to a product and they force everyone else to use it :). In this class, I do not force you to use a specific IDE because I know you will be switching to a different one in your major.
Here’s a non-comprehensive list of IDEs.
- RECOMMENDED: Anaconda IDE – https://www.anaconda.com/
- Project Jupyter | Home (supports more than just Python)
- IDLE — Python 3.9.1 documentation
- Home — Spyder IDE (spyder-ide.org)
- Visual Studio Code – Code Editing. Redefined
- Atom
- PyCharm: the Python IDE for Professional Developers by JetBrains
- Sublime Text – A sophisticated text editor for code, markup and prose
- PyDev
- Thonny, Python IDE for beginners
- Wing Python IDE – Designed for Python (wingware.com)
I cannot sit here and tell you which one to get, although I do recommend Anaconda for a good IDE and set of packages for data science and engineering. As I said previously, you will generally be forced to use one or another by your major department or your corporation. As computer scientists, we use ones that give us the feel for the underlying architecture, such as Atom or VS Code.
Again, this is all about car shopping. The point of the car is to transport you from point A to point B. The point of an IDE is to get you to run Python programs. How you go about doing that is more about style–which features you like and which you can live without.